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 view’s 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 view’s local table. You can index the materialized view’s 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) .

If it can perform a query rewrite.0. 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. By specifying REFRESH ON COMMIT in our original definition of the view.ORA file. 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. we requested that Oracle maintain synchronization between the view and the details. Oracle will insert an extra step into this process. So. Oracle 8i implements snapshots and materialized views as a single table.ORA parameter necessary for materialized views to function. a function will return a single value. when QUERY REWRITE ENABLED is set to FALSE. 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. PROCEDURE and PACKAGE. on commit refresh There is one mandatory INIT.1. in order for query rewrites to be functional. If it cannot rewrite the query. 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. the summary will be maintained as well. or above. now that we can create a materialized view and show that it works. the original parsed query is optimized and executed as normal Explain the difference between a FUNCTION. Keywords "snapshot" and "materialized views" can be used interchangeably. Oracle will attempt to rewrite the query to access some materialized view. Oracle will take your SQL as is. parse it. what are the steps Oracle will undertake to rewrite our queries? Normally. The value of COMPATIBLE should be set to 8. There are two other relevant parameters that may be set at either the system-level via the INIT.They are the same. query rewrite will not be invoked. If this value is not set appropriately. or the session-level via the ALTER SESSION command. The query plan with the lowest cost from this set is chosen for execution. like query rewrite. the rewritten query (or queries) is parsed and then optimized along with the original query. After parsing. determine free space in a tablespace? DBA_FREE_SPACE rebuild an index? . With query rewrites enabled. this is the COMPATIBLE parameter. and optimize it. previous releases implemented it as a view with an underlying SNAP$_% table. instead of the actual table that it references. While a procedure does not have to return any values to the calling application.

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

INSERT. and Row Chaining Overview of Views A view is a tailored presentation of the data contained in one or more tables or other views. Nonunique indexes do not impose this restriction on the column values. DBA_UPDATABLE_COLUMNS. CONNECT BY. Because a view is based on other objects. You can create indexes on one or more columns of a table to speed SQL statement execution on that table. a view can be thought of as a stored query or a virtual table. Therefore. 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. ROWNUM. Rather. a view is not allocated any storage space. An updatable join view is a join view that involves two or more base tables or views. Composite Indexes A composite index (also called a concatenated index) is an index that you create on multiple columns in a table. Unlike a table. Columns in a composite index can appear in any order . GROUP BY. and USER_UPDATABLE_COLUMNS contain information that indicates which of the view columns are updatable. You can use views in most places where a table can be used. Base tables can in turn be actual tables or can be views themselves (including materialized views). Unique indexes guarantee that no two rows of a table have duplicate values in the key column (or columns). In order to be inherently updatable. an Oracle index provides a faster access path to table data. nor does a view actually contain data. START WITH. CONNECT BY. and DELETE operations are permitted. "Dependencies Among Schema Objects" Overview of Views Schema Objects 5-21 _ A DISTINCT operator _ An aggregate or analytic function _ A GROUP BY. Indexes are the primary means of reducing disk I/O when properly used. Oracle provides several indexing schemes. 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. ORDER BY. a view requires no storage other than storage for the definition of the view (the stored query) in the data dictionary. The data dictionary views ALL_UPDATABLE_COLUMNS. aggregation.PCTFREE. 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. where UPDATE. INTERSECT. a view is defined by a query that extracts or derives data from the tables that the view references. and so on). PCTUSED. These tables are called base tables. A view takes the output of a query and treats it as a table. and set operations (UNION ALL. Just as the index in this manual helps you locate information faster than if there were no index. 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.

Besides storing the primary key column values of an index-organized table row. load data infile 'example. In a bitmap index. RAC Bitmap Indexes The purpose of an index is to provide pointers to the rows in a table that contain a given key value. If the number of different key values is small.and need not be adjacent in the table. 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. A mapping function converts the bit position to an actual rowid. Function-Based Indexes You can create indexes on functions and expressions that involve one or more columns in the table being indexed. reverses the bytes of each column indexed (except the rowid) while keeping the column order. Oracle stores each key value repeatedly with each stored rowid. this is achieved by storing a list of rowids for each key corresponding to the rows with that key value. Reverse Key Indexes Creating a reverse key index. You can create a function-based index as either a B-tree or a bitmap index. Unlike an ordinary (heap-organized) table whose data is stored as an unordered collection (heap). 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. data for an index-organized table is stored in a B-tree index structure in a primary key sorted manner. If the bit is set. each index entry in the B-tree stores the nonkey column values as well. now and in the future. A function-based index computes the value of the function or expression and stores it in the index. a bitmap for each key value is used instead of a list of rowids.' optionally enclosed by '"' (col1. col2)    Conventional Path Loads Direct Path Loads External Table Loads . so the bitmap index provides the same functionality as a regular index even though it uses a different representation internally.dat' "fix 11" into table example fields terminated by '. 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. In a regular index. Each bit in the bitmap corresponds to a possible rowid. compared to a standard index. then bitmap indexes are very space efficient. then it means that the row with the corresponding rowid contains the key value.

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

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. This method is no longer favoured by Oracle and will be desupported in future releases. you might be able to choose a more efficient execution plan than the optimizer. It's helpful if the join column is indexed from the larger table. Hints Hints let you make decisions usually made by the optimizer For example. The explain plan process stores data in the PLAN_TABLE. Nested loops are useful when joining a smaller table to a larger table. How to read multiple lines from the text file using PL/SQL In the previous article. If you are new to working with UTL_FILE. we shall work on more than one line (or read all lines) from the text file. looking up the join criteria in the larger 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. The index structure is not partitioned. This will often reveal that the query is not using the relevant indexes. 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. It gives you all the necessary steps for creating and developing PL/SQL with UTL_FILE for beginners. I strongly suggest you go through my first article in this series. use hints to force the optimizer to use the optimal execution plan. Hash joins read the smaller tables into a hash table in memory so the referenced records can be accessed quickly by the hash key. you might know that a certain index is more selective for certain queries.This method is used if the server has no internal statistics relating to the objects referenced by the statement. or indexes to support the query are missing.    Nested loops work from one table (preferably the smaller of the two). Merge joins work by selecting the result set from each table and then merging these two (or more) results. But no one would ever be happy working with only a single line.       ALL_ROWS -cost based FIRST_ROWS(n) CHOOSE RULE Rule Based Optimizer (RBO) . we have seen how to work with only the first line in the text file. 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. Merge joins are useful when joining two relatively large tables of about the same size. Based on this information. Interpretation of the execution plan is beyond the scope of this article. In this section. Hash joins are great in data warehouse scenarios. 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 method is used if internal statistics are present. The CBO checks several possible execution plans and selects the one with the lowest cost. Cost Based Optimizer (CBO) . Global Non-Partitioned Indexes: A global non-partitioned index is essentially identical to an index on a nonpartitioned table. . In such a case. where cost relates to system resources.

Implicit Cursors Whenever a SQL statement is directly in the execution or exception section of a PL/SQL block. PL/SQL immediately raises the NO_DATA_FOUND exception and control passes to the exception section.'R'). let us follow the sample code: declare f utl_file. or dynamic cursors.com/c/a/Oracle/Database-Interaction-with-PLSQL-Userdefined-Exceptions-Nested-Blocks/ Now. Dynamic cursors in PL/SQL are implemented via the built-in package DBMS_SQL. .We will also need to work with exceptions in this article.get_line(f. a cursor is a name assigned to a specific private SQL area for a specific SQL statement. FETCH.A SQL statement is dynamic if it is constructed at runtime and then executed. there are two types of SQL that you can execute in PL/SQL: dynamic . When an implicit SELECT statement does not return any rows. you are working with implicit cursors.devshed.fclose(f). Explicit cursors are SELECT statements that are DECLAREd explicitly in the declaration section of the current block or in a package specification. Dynamic SQL is made possible in PL/SQL only through the use of the DBMS SQL built-in package. dbms_output.com/c/a/Oracle/Database-Interaction-with-PLSQLPredefined-Exceptions/ http://www. implicit cursors do not need to be declared. loop utl_file. Generally. When an implicit SELECT returns more than one row. end loop. Unlike explicit cursors.SQL is static if the content of the SQL statement is determined at compile time. In PL/SQL.'sample1. Static cursors are covered in greater detail in this section.  A cursor without parameters. static . If you are new to exception handling in PL/SQL. SELECT statements handle the %FOUND and %NOTFOUND attributes differently from explicit cursors. and SELECT INTO statements.s). I strongly suggest you refer to my contributions at: http://www. whose SQL statement is determined at compile time.devshed.fopen('SAMPLEDATA'. such as: CURSOR company_cur IS SELECT company_id FROM company. All other forms of SQL executed inside a PL/SQL program represent static SQL. or CLOSEd. These statements include INSERT.put_line(s). Use OPEN. DELETE. UPDATE. end. PL/SQL immediately raises the TOO_MANY_ROWS exception and control passes to the exception section. and CLOSE in the execution or exception sections of your programs. 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.txt'. begin f := utl_file. There can be either static cursors. s varchar2(200). exception when NO_DATA_FOUND then utl_file. FETCHed.file_type. whose SQL statement is determined at runtime. OPENed.

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

Exceptions An Exception is an error situation. Procedure specification begins with CREATE and ends with procedure name or parameters list.. which is used to compute a value.. which is raised automatically when we try to divide a number by zero. Procedures that do not take parameters are written without a parenthesis. These distinctions are shown in the diagram below. A procedure contains two parts specification and the body.the result set identified by the cursor SQL statement. Other built-in exceptions are given below. you must instead use the OPEN FOR syntax to create a new cursor object and assign it to the variable. all of the same type. normal execution is stopped and control transfers to exception-handling part. . 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. It can handle all raised exceptions that are not handled by any other handler. Declaration of a cursor variable does not create a cursor object. Predefined exception is raised automatically whenever there is a violation of Oracle coding rules. Just as a variable points to a value. BEGIN . The body of the procedure starts after the keyword IS or AS and ends with keyword END.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. It is very important to distinguish between declaring a cursor variable and creating an actual cursor object -. Exception handlers are routines written to handle the exception. whereas a constant is the value. so does a cursor variable refer to a cursor object. To do that. /* Create a cursor variable for sports cars. Function is same like a procedure except for the difference that it have RETURN clause. Note that two different cursor variables in different programs can both refer to the same cursor object. END. */ sports_car_cur sports_car_cur_type. Here is an example of the creation of a cursor variable: DECLARE /* Create a cursor type for sports cars. Predefined exceptions are those like ZERO_DIVIDE. which arises during program execution. A collection is defined as an ordered group of elements. The exceptions can be internally defined (system-defined or pre-defined) or User-defined exception. The cursor variable is nothing more than a reference or pointer. Functions: A function is a PL/SQL subprogram. You can handle unexpected Oracle errors using OTHERS handler. Individual element in a collection can be accessed by using index like an array in C. */ TYPE sports_car_cur_type IS REF CURSOR RETURN car%ROWTYPE. There are three types of collections in oracle Procedures Procedure is a subprogram used to perform a specific action. When an error occurs exception is raised.

Sign up to vote on this title
UsefulNot useful