Sie sind auf Seite 1von 10

Snapshot and Materialised view A materialized view is a table that stores derived data.

During its creation, you specify the SQL used to populate the materialized view. For a large database, a materialized view may offer several performance advantages. Depending on the complexity of the base SQL, you may be able to populate the materialized view with incremental changes (via a materialized view log) instead of completely re-creating it during data refreshes. Unlike snapshots, materialized views can be used dynamically by the optimizer to change the execution paths for queries. This feature, called query rewrite, enables the optimizer to use a materialized view in place of the table queried by the materialized view, even if the materialized view is not named in the query. For example, if you have a large SALES table, you may create a materialized view that sums the SALES data by region. If a user queries the SALES table for the sum of the SALES data for a region, ORACLE can redirect that query to use your materialized view in place of the SALES table. As a result, you can reduce the number of accesses against your largest tables, improving the system performance. To enable a materialized view for query rewrite, all of the master tables for the materialized view must be in the materialized views schema, and you must have the QUERY REWRITE system privilege. If the view and the tables are in separate schemas, you must have the GLOBAL QUERY REWRITE system privilege. In general, you should create materialized views in the same schema as the tables on which they are based; otherwise, you will need to manage the permissions and grants required to create and maintain the materialized view. Like a snapshot, a materialized view creates a local table to store the data and a view that accesses that data. Depending on the complexity of the materialized view, ORACLE may also create an index on the materialized views local table. You can index the materialized views local table to improve the performance of queries against the materialized view. To create a materialized view, use the create materialized view command. The example shown in the following listing creates a materialized view against the SALES table: create materialized view SALES_MONTH_MV tablespace AGG_DATA refresh complete start with sysdate next sysdate+1 enable query rewrite as select Sales_Month, SUM(Amount) from SALES group by Sales_Month; As shown in the preceding listing, the create materialized view command specifies the name of the view and its refresh schedule. In this example, a complete refresh of the view is chosen-each time the view is refreshed, its data will be completely deleted and re-created. For views that are not based on aggregations, you can use fast refreshes in combination with materialized view logs to send only incremental changes to the materialized view. The start with and next clauses tell ORACLE when to schedule refreshes of the data. The data will be automatically refreshed if you have enabled background job processes (via the JOB_QUEUE_PROCESSES init.ora parameter). The tablespace clause tells ORACLE where to store the local table for the materialized view. The enable query rewrite clause enables the optimizer to redirect queries of SALES to SALES_MONTH_MV if appropriate. The full syntax for creating materialized views is found online in Oracle8i SQL Reference (requires a Technet login) . Fast refreshes of materialized views use materialized view logs. A materialized view log is a table stored along with the master table for the materialized view. As rows change in the master table, the changes are written to the materialized view log. During a fast refresh, the changed rows from the master table, as identified via the materialized view log, are sent to the materialized view. If the changes account for less than 25 percent of the rows in the master table, a fast refresh is generally faster than a complete refresh. For the full syntax of the create materialized view log command, see Oracle8i SQL Reference (requires a Technet login) .

They are the same. Keywords "snapshot" and "materialized views" can be used interchangeably. Oracle 8i implements snapshots and materialized views as a single table, previous releases implemented it as a view with an underlying SNAP$_% table. like query rewrite, on commit refresh

There is one mandatory INIT.ORA parameter necessary for materialized views to function, this is the COMPATIBLE parameter. The value of COMPATIBLE should be set to 8.1.0, or above, in order for query rewrites to be functional. If this value is not set appropriately, query rewrite will not be invoked. There are two other relevant parameters that may be set at either the system-level via the INIT.ORA file, or the session-level via the ALTER SESSION command. By specifying REFRESH ON COMMIT in our original definition of the view, we requested that Oracle maintain synchronization between the view and the details, the summary will be maintained as well. So, now that we can create a materialized view and show that it works, what are the steps Oracle will undertake to rewrite our queries? Normally, when QUERY REWRITE ENABLED is set to FALSE, Oracle will take your SQL as is, parse it, and optimize it. With query rewrites enabled, Oracle will insert an extra step into this process. After parsing, Oracle will attempt to rewrite the query to access some materialized view, instead of the actual table that it references. If it can perform a query rewrite, the rewritten query (or queries) is parsed and then optimized along with the original query. The query plan with the lowest cost from this set is chosen for execution. If it cannot rewrite the query, the original parsed query is optimized and executed as normal Explain the difference between a FUNCTION, PROCEDURE and PACKAGE. A function and procedure are the same in that they are intended to be a collection of PL/SQL code that carries a single task. While a procedure does not have to return any values to the calling application, a function will return a single value. A package on the other hand is a collection of functions and procedures that are grouped together based on their commonality to a business function or application encrypt a PL/SQL application? WRAP How would you determine what sessions are connected and what resources they are waiting for? Use of V$SESSION and V$SESSION_WAIT background process refreshes materialized views? The Job Queue Processes. coalescing a tablespace do? Coalescing is only valid for dictionary-managed tablespaces and de-fragments space by combining neighboring free extents into large single extents. the difference between a TEMPORARY tablespace and a PERMANENT tablespace? A temporary tablespace is used for temporary objects such as sort structures while permanent tablespaces are used to store those objects meant to be used as the true objects of the database. determine free space in a tablespace? DBA_FREE_SPACE rebuild an index?

ALTER INDEX <index_name> REBUILD; determine what DDL changes have been made. You could use Logminer or Streams you determine who has added a row to a table? Turn on fine grain auditing for the table. just compiled a PL/SQL package but got errors, how would you view the errors? SHOW ERRORS gather statistics on a table? The ANALYZE command. a trace for a session? Use the DBMS_SESSION.SET_SQL_TRACE or Use ALTER SESSION SET SQL_TRACE = TRUE; network connection to a database. TNSNAMES.ORA and SQLNET.ORA inline view is a view which will be created using sub queries instead of table names in the database for performance enhancements. Trigger You can write triggers that fire whenever one of the following operations occurs: 1. DML statements (INSERT, UPDATE, DELETE) on a particular table or view, issued by any user 2. DDL statements (CREATE or ALTER primarily) issued either by a particular schema/user or by any schema/user in the database 3. Database events, such as logon/logoff, errors, or startup/shutdown, also issued either by a particular schema/user or by any schema/user in the database Triggers are similar to stored procedures. A trigger stored in the database can include SQL and PL/SQL or Java statements to run as a unit and can invoke stored procedures. However, procedures and triggers differ in the way that they are invoked. A procedure is explicitly run by a user, application, or trigger. Triggers are implicitly fired by Oracle when a triggering event occurs, no matter which user is connected or which application is being used. At the finest level of granularity, Oracle stores data in data blocks (also called logical blocks, Oracle blocks, or pages). One data block corresponds to a specific number of bytes of physical database space on disk. The next level of logical database space is an extent. An extent is a specific number of contiguous data blocks allocated for storing a specific type of information. The level of logical database storage greater than an extent is called a segment. A segment is a set of extents, each of which has been allocated for a specific data structure and all of which are stored in the same tablespace. For example, each tables data is stored in its own data segment, while each indexs data is stored in its own index segment. If the table or index is partitioned, each partition is stored in its own segment.

PCTFREE, PCTUSED, and Row Chaining Overview of Views A view is a tailored presentation of the data contained in one or more tables or other views. A view takes the output of a query and treats it as a table. Therefore, a view can be thought of as a stored query or a virtual table. You can use views in most places where a table can be used. Unlike a table, a view is not allocated any storage space, nor does a view actually contain data. Rather, a view is defined by a query that extracts or derives data from the tables that the view references. These tables are called base tables. Base tables can in turn be actual tables or can be views themselves (including materialized views). Because a view is based on other objects, a view requires no storage other than storage for the definition of the view (the stored query) in the data dictionary. Updatable Join Views A join view is defined as a view that has more than one table or view in its FROM clause (a join) and that does not use any of these clauses: DISTINCT, aggregation, GROUP BY, START WITH, CONNECT BY, ROWNUM, and set operations (UNION ALL, INTERSECT, and so on). An updatable join view is a join view that involves two or more base tables or views, where UPDATE, INSERT, and DELETE operations are permitted. The data dictionary views ALL_UPDATABLE_COLUMNS, DBA_UPDATABLE_COLUMNS, and USER_UPDATABLE_COLUMNS contain information that indicates which of the view columns are updatable. In order to be inherently updatable, a view cannot contain any of the following constructs: _ A set operator See Also: Oracle Database Performance Tuning Guide for more information about query optimization See Also: Chapter 6, "Dependencies Among Schema Objects" Overview of Views Schema Objects 5-21 _ A DISTINCT operator _ An aggregate or analytic function _ A GROUP BY, ORDER BY, CONNECT BY, or START WITH clause _ A collection expression in a SELECT list _ A subquery in a SELECT list _ Joins (with some exceptions) Overview of Indexes Indexes are optional structures associated with tables and clusters. You can create indexes on one or more columns of a table to speed SQL statement execution on that table. Just as the index in this manual helps you locate information faster than if there were no index, an Oracle index provides a faster access path to table data. Indexes are the primary means of reducing disk I/O when properly used. Oracle provides several indexing schemes, which provide complementary performance functionality: _ B-tree indexes _ B-tree cluster indexes _ Hash cluster indexes _ Reverse key indexes _ Bitmap indexes _ Bitmap join indexes Unique and Nonunique Indexes Indexes can be unique or nonunique. Unique indexes guarantee that no two rows of a table have duplicate values in the key column (or columns). Nonunique indexes do not impose this restriction on the column values. Composite Indexes A composite index (also called a concatenated index) is an index that you create on multiple columns in a table. Columns in a composite index can appear in any order

and need not be adjacent in the table. Function-Based Indexes You can create indexes on functions and expressions that involve one or more columns in the table being indexed. A function-based index computes the value of the function or expression and stores it in the index. You can create a function-based index as either a B-tree or a bitmap index. DETERMINISTIC Functions Any user-written function used in a function-based index must have been declared with the DETERMINISTIC keyword to indicate that the function will always return the same output return value for any given set of input argument values, now and in the future. Reverse Key Indexes Creating a reverse key index, compared to a standard index, reverses the bytes of each column indexed (except the rowid) while keeping the column order. RAC Bitmap Indexes The purpose of an index is to provide pointers to the rows in a table that contain a given key value. In a regular index, this is achieved by storing a list of rowids for each key corresponding to the rows with that key value. Oracle stores each key value repeatedly with each stored rowid. In a bitmap index, a bitmap for each key value is used instead of a list of rowids. Each bit in the bitmap corresponds to a possible rowid. If the bit is set, then it means that the row with the corresponding rowid contains the key value. A mapping function converts the bit position to an actual rowid, so the bitmap index provides the same functionality as a regular index even though it uses a different representation internally. If the number of different key values is small, then bitmap indexes are very space efficient. Bitmap indexes include rows that have NULL values Index-Organized Tables An index-organized table has a storage organization that is a variant of a primary B-tree. Unlike an ordinary (heap-organized) table whose data is stored as an unordered collection (heap), data for an index-organized table is stored in a B-tree index structure in a primary key sorted manner. Besides storing the primary key column values of an index-organized table row, each index entry in the B-tree stores the nonkey column values as well. SQL Loader SQL*Loader loads data from external files into tables of an Oracle database. It has a powerful data parsing engine that puts little limitation on the format of the data in the datafile. load data infile 'example.dat' "fix 11" into table example fields terminated by ',' optionally enclosed by '"' (col1, col2) Conventional Path Loads Direct Path Loads External Table Loads

Partitioning Oracle Partitioning, an option of Oracle9i Enterprise Edition, can enhance the manageability, performance, and availability of a wide variety of applications. Partitioning allows tables, indexes, and index-organized tables to be subdivided into smaller pieces, enabling these database objects to be managed and accessed at a finer level of granularity. Oracle provides a rich variety of partitioning schemes to address every business requirement Partitioning allows a table, index or index-organized table to be subdivided into smaller pieces. Each piece of database object is called a partition. Each partition has its own name, and may optionally have its own storage characteristics, such as having table compression enabled or being stored in different tablespaces. From the perspective of a database administrator, a partitioned object has multiple pieces which can be managed either collectively or individually. Tables are partitioned using a 'partitioning key', a set of columns which determine in which partition a given row will reside Range Partitioning: Each partition is specified by a range of values of the partitioning key (for a table with a date column as the partitioning key, the 'January-2001' partition contains rows with the partitioning-key values from '01-JAN-2001' - '31-JAN-2001') List Partitioning: Each partition is specified by a list of values of the partitioning key (for a table with a region column as the partitioning key, the 'North America' partition may contain values 'Canada', 'USA', and 'Mexico') Hash Partitioning: A hash algorithm is applied to the partitioning key to determine the partition for a given row Composite Range-Hash Partitioning: A combination of the Range and Hash partitioning technique. The table is first range-partitioned, and then each individual range-partition is further sub-partitioned using the hash partitioning technique. All sub-partitions for a given range partition together represent a logical subset of the data. Composite Range-List Partitioning: A combination of the Range and List partitioning technique. The table is first range-partitioned, and then each individual range-partition is further sub-partitioned using a list partitioning technique. Unlike composite Range-Hash partitioning, the content of each sub-partition represents a logical subset of the data, described by its appropriate Range and List partition setup. Local Indexes: A local index is an index on a partitioned table which is partitioned in the exact same manner as the underlying partitioned table. Each partition of a local index corresponds to one and only one partition of the underlying table. Global Partitioned Indexes: A global partitioned index is an index on a partitioned or non-partitioned table which is partitioned using a different partitioning-key from the table. Global-partitioned indexes can only be partitioned using range partitioning. For example, a table could be range-partitioned by month and have twelve partitions, while an index on that table could be range-partitioned using a different partitioning key and have a different number of partitions.

Global Non-Partitioned Indexes: A global non-partitioned index is essentially identical to an index on a nonpartitioned table. The index structure is not partitioned.

Hints Hints let you make decisions usually made by the optimizer For example, you might know that a certain index is more selective for certain queries. Based on this information, you might be able to choose a more efficient execution plan than the optimizer. In such a case, use hints to force the optimizer to use the optimal execution plan. ALL_ROWS -cost based FIRST_ROWS(n) CHOOSE RULE Rule Based Optimizer (RBO) - This method is used if the server has no internal statistics relating to the objects referenced by the statement. This method is no longer favoured by Oracle and will be desupported in future releases. Cost Based Optimizer (CBO) - This method is used if internal statistics are present. The CBO checks several possible execution plans and selects the one with the lowest cost, where cost relates to system resources.

Explain Plan When an SQL statement is passed to the server the Cost Based Optimizer (CBO) uses database statistics to create an execution plan which it uses to navigate through the data. Once you've highlighted a problem query the first thing you should do is EXPLAIN the statement to check the execution plan that the CBO has created. This will often reveal that the query is not using the relevant indexes, or indexes to support the query are missing. Interpretation of the execution plan is beyond the scope of this article. The explain plan process stores data in the PLAN_TABLE. This table can be located in the current schema or a shared schema and is created using in SQL*Plus as follows: Switching on the AUTOTRACE parameter in SQL*Plus causes an explain to be performed on every query.

Nested loops work from one table (preferably the smaller of the two), looking up the join criteria in the larger table. It's helpful if the join column is indexed from the larger table. Nested loops are useful when joining a smaller table to a larger table. Merge joins work by selecting the result set from each table and then merging these two (or more) results. Merge joins are useful when joining two relatively large tables of about the same size. Hash joins read the smaller tables into a hash table in memory so the referenced records can be accessed quickly by the hash key. Hash joins are great in data warehouse scenarios, in which several smaller tables (with referential integrity defined) are being referenced in the same SQL query as a single larger or very large table.

Package Writing to Text Files in Oracle PL/SQL (Page 1 of 6 ) This is the second article in a series focusing on file input/output using Oracle PL/SQL packages. If you are new to working with UTL_FILE, I strongly suggest you go through my first article in this series. It gives you all the necessary steps for creating and developing PL/SQL with UTL_FILE for beginners. How to read multiple lines from the text file using PL/SQL In the previous article, we have seen how to work with only the first line in the text file. But no one would ever be happy working with only a single line. In this section, we shall work on more than one line (or read all lines) from the text file.

We will also need to work with exceptions in this article. If you are new to exception handling in PL/SQL, I strongly suggest you refer to my contributions at: http://www.devshed.com/c/a/Oracle/Database-Interaction-with-PLSQLPredefined-Exceptions/ http://www.devshed.com/c/a/Oracle/Database-Interaction-with-PLSQL-Userdefined-Exceptions-Nested-Blocks/ Now, let us follow the sample code: declare f utl_file.file_type; s varchar2(200); begin f := utl_file.fopen('SAMPLEDATA','sample1.txt','R'); loop utl_file.get_line(f,s); dbms_output.put_line(s); end loop; exception when NO_DATA_FOUND then utl_file.fclose(f); end; Cursor Every SQL statement executed by the RDBMS has a private SQL area that contains information about the SQL statement and the set of data returned. In PL/SQL, a cursor is a name assigned to a specific private SQL area for a specific SQL statement. There can be either static cursors, whose SQL statement is determined at compile time, or dynamic cursors, whose SQL statement is determined at runtime. Static cursors are covered in greater detail in this section. Dynamic cursors in PL/SQL are implemented via the built-in package DBMS_SQL. Generally, there are two types of SQL that you can execute in PL/SQL: dynamic - A SQL statement is dynamic if it is constructed at runtime and then executed. Dynamic SQL is made possible in PL/SQL only through the use of the DBMS SQL built-in package. All other forms of SQL executed inside a PL/SQL program represent static SQL. static - SQL is static if the content of the SQL statement is determined at compile time.

Implicit Cursors Whenever a SQL statement is directly in the execution or exception section of a PL/SQL block, you are working with implicit cursors. These statements include INSERT, UPDATE, DELETE, and SELECT INTO statements. Unlike explicit cursors, implicit cursors do not need to be declared, OPENed, FETCHed, or CLOSEd. SELECT statements handle the %FOUND and %NOTFOUND attributes differently from explicit cursors. When an implicit SELECT statement does not return any rows, PL/SQL immediately raises the NO_DATA_FOUND exception and control passes to the exception section. When an implicit SELECT returns more than one row, PL/SQL immediately raises the TOO_MANY_ROWS exception and control passes to the exception section. Explicit cursors are SELECT statements that are DECLAREd explicitly in the declaration section of the current block or in a package specification. Use OPEN, FETCH, and CLOSE in the execution or exception sections of your programs.

A cursor without parameters, such as: CURSOR company_cur IS SELECT company_id FROM company;

A cursor that accepts arguments through a parameter list:

CURSOR company_cur (id_in IN NUMBER) IS SELECT name FROM company WHERE company_id = id_in; There are four attributes associated with cursors: ISOPEN, FOUND, NOTFOUND, and ROWCOUNT.\ DECLARE /* Explicit declaration of a cursor */ CURSOR emptyp_cur IS SELECT emptyp.type_desc FROM employees emp, employee_type emptyp WHERE emp.type_code = emptyp.type_code; BEGIN /* Check to see if cursor is already open. If not, open it. */ IF NOT emptyp_cur%ISOPEN THEN OPEN emptyp_cur; END IF; /* Fetch row from cursor directly into an Oracle Forms item */ FETCH emptyp_cur INTO :emp.type_desc; /* Close the cursor */ CLOSE emptyp_cur; END; Use DBMS_PROFILER to profile and tune PL/SQL programs Declaring REF CURSOR Types and Cursor Variables Just as with a PL/SQL table or a programmer-defined record, you must perform two distinct declaration steps in order to create a cursor variable. Create a referenced cursor TYPE. Declare the actual cursor variable based on that type. The syntax for creating a referenced cursor type is as follows: TYPE cursor_type_name IS REF CURSOR [ RETURN return_type ]; where cursor_type_name is the name of the type of cursor and return_type is the RETURN data specification for the cursor type. The return_type can be any of the data structures valid for a normal cursor RETURN clause, defined using the %ROWTYPE attribute or by referencing a previously-define record TYPE. Notice that the RETURN clause is optional with the REF CURSOR type statement. Both of the following declarations are valid: TYPE company_curtype IS REF CURSOR RETURN company%ROWTYPE; --strong type TYPE generic_curtype IS REF CURSOR; --weak type The first form of the REF CURSOR statement is called a strong type because it attaches a record type (or row type) to the cursor variable type at the moment of declaration. Any cursor variable declared using that type can only be used with SQL statements and FETCH INTO data structures which match the specified record type. The second form of the REF CURSOR statement, in which the RETURN clause is missing, is called a weak type. This cursor variable type is not associated with any record data structure. Cursor variables declared without the RETURN clause can be used in much more flexible ways than the strong type. They can be used with any query, with any rowtype structure -- varying even within the course of a single program. Declaring the Cursor Variable The syntax for declaring a cursor variable is: cursor_name cursor_type_name;

where cursor_name is the name of the cursor and cursor_type_name is the name of the type of cursor previously defined with a TYPE statement. Here is an example of the creation of a cursor variable: DECLARE /* Create a cursor type for sports cars. */ TYPE sports_car_cur_type IS REF CURSOR RETURN car%ROWTYPE; /* Create a cursor variable for sports cars. */ sports_car_cur sports_car_cur_type; BEGIN ... END; It is very important to distinguish between declaring a cursor variable and creating an actual cursor object -- the result set identified by the cursor SQL statement. The cursor variable is nothing more than a reference or pointer. Just as a variable points to a value, whereas a constant is the value, so does a cursor variable refer to a cursor object. These distinctions are shown in the diagram below. Note that two different cursor variables in different programs can both refer to the same cursor object.

Declaration of a cursor variable does not create a cursor object. To do that, you must instead use the OPEN FOR syntax to create a new cursor object and assign it to the variable.

Exceptions An Exception is an error situation, which arises during program execution. When an error occurs exception is raised, normal execution is stopped and control transfers to exception-handling part. Exception handlers are routines written to handle the exception. The exceptions can be internally defined (system-defined or pre-defined) or User-defined exception. Predefined exception is raised automatically whenever there is a violation of Oracle coding rules. Predefined exceptions are those like ZERO_DIVIDE, which is raised automatically when we try to divide a number by zero. Other built-in exceptions are given below. You can handle unexpected Oracle errors using OTHERS handler. It can handle all raised exceptions that are not handled by any other handler. It must always be written as the last handler in exception block PL/SQL Collections:

A collection is a data structure that acts like an array. A collection is defined as an ordered group of elements, all of the same type. Individual element in a collection can be accessed by using index like an array in C. There are three types of collections in oracle Procedures

Procedure is a subprogram used to perform a specific action. A procedure contains two parts specification and the body. Procedure specification begins with CREATE and ends with procedure name or parameters list. Procedures that do not take parameters are written without a parenthesis. The body of the procedure starts after the keyword IS or AS and ends with keyword END. Functions:

A function is a PL/SQL subprogram, which is used to compute a value. Function is same like a procedure except for the difference that it have RETURN clause.

Das könnte Ihnen auch gefallen