Jun 29, 2011

UNDERSTANDING EXPLAIN PLAN 1



 UNIQUE
Sorts to eliminate duplicate rows. This typically occurs as a result of using the DISTINCT clause.


SORT UNIQUE sorts result sets and eliminates duplicate records prior to processing with the MINUS, INTERSECTION and UNION operations.

Example

A MINUS operation will be used in this example, although the SORT UNIQUE operation is also used in the INTERSECTION and UNION operation.
select Company_ID  from COMPANY
MINUS
select Company_ID from COMPETITOR;

Execution Plan

PROJECTION
MINUS
SORT UNIQUE
TABLE ACCESS FULL COMPANY
SORT UNIQUE
TABLE ACCESS FULL COMPETITOR

Interpreting the Execution Plan

The Execution Plan shows that after each of the queries is separately resolved (by the TABLE ACCESS FULL operations), the records are passed to the SORT UNIQUE operation prior to being input into the MINUS operation. The SORT UNIQUE operation sorts the records and eliminates any duplicates, then sends the records to the MINUS operation.
SAME IN THE CASE FOR INTERSECT ALSO.
FOR  UNION
select Company_ID  from COMPANY
UNION
select Company_ID from COMPETITOR;

Execution Plan

PROJECTION
SORT UNIQUE
UNION -ALL
TABLE ACCESS FULL COMPANY
TABLE ACCESS FULL COMPETITOR
For UnionAll operation there will not be SORT-UNIQUE OPERATION IN EXPLAIN PLAN
GROUP BY
Sorts a result set to group it for the GROUP BY clause.
SORT GROUP BY performs grouping functions on sets of records.

Example

select Zip, COUNT(*) from COMPANY group by Zip;

Execution Plan

SORT GROUP BY
TABLE ACCESS FULL COMPANY
GROUP BY  NOSORT
GROUP BY clause that does not require a sort operation.
One cause of sorting is when indexes are created . Creating an index for a table involves sorting all of the rows in a table based on the values of the indexed columns. Oracle also allows you to create indexes without sorting, using the SORT GROUP BY NOSORT operation. When the rows in the table are loaded in ascending order, you can create the index faster without sorting.

NOSORT Clause

To create an index without sorting, load the rows into the table in ascending order of the indexed column values. Your operating system may provide a sorting utility to sort the rows before you load them. When you create the index, use the NOSORT clause on the CREATE INDEX statement. For example, this CREATE INDEX statement creates the index EMP_INDEX on the ENAME column of the emp table without sorting the rows in the EMP table:
CREATE INDEX emp_index ON emp(ename)  NOSORT;

When to Use the NOSORT Clause

Presorting your data and loading it in order may not always be the fastest way to load a table. When you have a multiple-CPU computer, you may be able to load data faster using multiple processors in parallel, each processor loading a different portion of the data. To take advantage of parallel processing, load the data without sorting it first. Then create the index without the NOSORT clause. When you have a single-CPU computer, you should sort your data before loading, when possible. Then create the index by using the NOSORT clause.

GROUP BY NOSORT

Sorting can be avoided when performing a GROUP BY operation when you know that the input data is already ordered, so that all rows in each group are clumped together. This may be the case when the rows are being retrieved from an index that matches the grouped columns, or when a sort-merge join produces the rows in the right order. ORDER BY sorts can be avoided in the same circumstances. When no sort takes place, the Explain Plan output indicates GROUP BY NOSORT.
GROUP BY ROLLUP
GROUP BY clause that includes the ROLLUP option.
SORT GROUP BY ROLLUP enables a SELECT statement to calculate multiple levels of subtotals across a specified group of dimensions. It also calculates a grand total. ROLLUP is a simple extension to the GROUP BY clause, so its syntax is extremely easy to use. The ROLLUP extension is highly efficient, adding minimal overhead to a query. For example, ROLLUP appears in the GROUP BY clause in a SELECT statement. ROLLUP creates subtotals at n+1 levels, where n is the number of grouping columns. For instance, if a query specifies ROLLUP on grouping columns of Time, Region, and Department (n=3), the result set will include rows at four aggregation levels.
GROUP BY CUBE
GROUP BY clause that includes the CUBE option.

The subtotals created by ROLLUP represent only a fraction of the possible subtotal combinations. The easiest way to generate the full set of subtotals needed for cross-tabular reports is to use the CUBE extension.
CUBE enables a SELECT statement to calculate subtotals for all of the possible combinations of a group of dimensions. It also calculates a grand total. This is the set of information typically needed for all cross-tabular reports, so CUBE can calculate a cross-tabular report with a single SELECT statement. Like ROLLUP, CUBE is a simple extension to the GROUP BY clause. When n columns are specified for a CUBE, there will be 2n combinations of subtotals returned.
 .
Index Operations
 .
AND-EQUAL
Combines the results from one or more index scans.
INDEX
Indicates an index lookup.

The following INDEX options are available:
Option
Description
Where Clause Example
SINGLE VALUE
Access a single value in the index and return a bitmap for all the matching rows.
Where State = ‘MD’
FULL SCAN
A complete scan of the index to find any matching values.
Where State not in (‘HI’, ‘AL’)
RANGE SCAN
Access a range of values in the index and return multiple bitmaps. These bitmaps are then merged into one bitmap.
Where City like ‘New*’
 .
INDEX UNIQUE SCAN
An index lookup that returns the address (ROWID) of only one row.
INDEX UNIQUE SCAN, which selects a unique value from a unique index, is the most efficient method of selecting a row from known field values.
Each unique index access is built from a separate access into the index’s B*-tree structure, drilling down from the index root to the leaf blocks. On average, three blocks are read to fulfill the unique index access.

Example

select Name, City, State from COMPANY where Company_ID = 12345;

Execution Plan

TABLE ACCESS BY ROWID COMPANY
INDEX UNIQUE SCAN COMPANY_PK

Interpreting the Execution Plan

The query uses the COMPANY_ID column as the sole criteria in its WHERE clause. Since COMPANY_ID is the primary key of the COMPANY table, it has a unique index associated with it. The unique index for the COMPANY_ID primary key is named COMPANY_PK.
During the query, the COMPANY_PK index is scanned for one COMPANY_ID value (12345). When the COMPANY_ID value is found, the ROWID associated with that COMPANY_ID is used to query the COMPANY table. 
.
RANGE SCAN
Returns the ROWID of more than one row. This can occur because the index is non-unique or because a range operator (>) was used. Indexed values are scanned in ascending order.
 .
INDEX RANGE SCAN selects a range of values from an index; the index can be either unique or non-unique. Range scans are used when one of the following conditions are met:
·         A range operator (such as < or >) is used.
·         The BETWEEN clause is used.
·         A search string with a wildcard is used (such as A*).
·         Only part of a concatenated index is used (such as by using only the leading column of a two-column index).
·         The access to the range of values within the index starts with an index search for the first row that is included in the range. After the first row has been located, there is a "horizontal" scan of the index blocks until the last row inside the range is found.
·         Note: The efficiency of an INDEX RANGE SCAN is directly related to two factors: (1) the number of keys in the selected range (the more values, the longer the search), (2) the condition of the index (the more fragmented, the longer the search).
The access to the range of values within the index starts with an index search for the first row that is included in the range. After the first row has been located, there is a "horizontal" scan of the index blocks until the last row inside the range is found.
Note: The efficiency of an INDEX RANGE SCAN is directly related to two factors: (1) the number of keys in the selected range (the more values, the longer the search), (2) the condition of the index (the more fragmented, the longer the search).

Example

select Name, City, State  from COMPANY where City > ‘Roanoke’;

Execution Plan

TABLE ACCESS BY ROWID COMPANY
INDEX RANGE SCAN COMPANY$CITY

Interpreting the Execution Plan

The Execution Plan shows that the index on the City column is used to find ROWIDs in the COMPANY table that satisfies the limiting condition on the City value. Since a range of values is specified City > ‘Roanoke’, an INDEX RANGE SCAN is performed. The first value that falls within the range is found in the index; the rest of the index is then searched for the remaining values. For each matching value, the ROWID is recorded. The ROWIDs from the INDEX RANGE SCAN are used to query the COMPANY table for the Name and State values. 
.
RANGE SCAN (MIN/MAX)
Finds the highest or lowest index entry in the range.

RANGE SCAN DESCENDING
Retrieves one or more ROWIDs from an index. Indexed values are scanned in descending order.
FULL SCAN
Scans every entry in the index in key order.


.


Reading rows in key order requires a block-by-block full scan of the index, which is incompatible with the Fast Full Scan. Although the fast full scan is much more efficient than the "normal" full index scan, the fast full scan does not return rows in index order.
Although using an index can eliminate the need to perform a sort, the overhead of reading all the index blocks and all the table blocks may be greater than the overhead of performing the sort. However, using the index should result in a faster retrieval of the first row since as soon as the row is retrieved it may be returned, whereas the sort approach will require that all rows be retrieved before the first row is returned. As a result, the cost based optimizer will tend to use the index if the optimizer goal is FIRST ROWS, but will choose a full table scan if the goal is ALL ROWS.
A way of avoiding both sort and table lookup overhead is to create an index which contains all the columns in the select list as well as the columns in the ORDER BY clause. Oracle can then resolve the query by using an index lookup alone.
Using an index to avoid a sort will lead to vastly superior response time (time to retrieve the first row) but much poorer throughput (time to retrieve the last row).
.
FULL SCAN (MIN/MAX)
Finds the highest or lowest index entry.

FULL SCAN DESCENDING
Finds one or more index entries. Index entries are scanned in descending order.

FAST FULL SCAN
Scans every entry in the index in block order, possibly using multi-block read.
 .
There are many examples in which an index alone has been used to resolve a query. Providing all the columns needed to resolve the query are in the index, there is no reason why Oracle cannot use the index alone to generate the result set.
The FAST FULL INDEX SCAN operation improves the efficiency of queries that can be resolved by reading an entire index. FAST FULL INDEX SCAN offers some significant advantages over other index scan methods, as follows:
·         In an index range scan or full index scan, index blocks are read in key order, one at a time. In a full fast scan, blocks are read in the order in which they appear on disk. Oracle is able to read multiple blocks in a single I/O - depending on the value of the server parameter DB_FILE_MULTIBLOCK_READ_COUNT (multi-block reads are discussed further later in this chapter).
·         The fast full index scan can be performed in parallel, while an index range scan or full index scan can only be processed serially. That is, Oracle can allocate multiple processes to perform a fast full index scan, but can only use a single process for traditional index scans.
Although a full table scan can use parallelism and multi-block read techniques, the number of blocks in a table will typically be many times the number of blocks in an index. The fast full index scan will therefore usually outperform an equivalent full table scan.
·         You can consider a fast full index scan in the following circumstances:
·         All the columns required to satisfy the query are included in the index.
·         At least one of the columns in the index is defined as NOT NULL.
·         The query will return more than 10-20* of the rows in the index.
·         The cost based optimizer can use the fast full scan as it sees fit unless you have FAST_FULL_SCAN_ENABLED=FALSE or V733_PLANS_ENABLED=FALSE (depending on your version of Oracle).
The Index fast full scan can take advantage of optimizations normally only available to table scans, such as multi-block read and parallel query. Counting the number of rows in a table is a perfect application for the fast full scan because there will almost always be an index on a NOT NULL column which could be used to resolve the query.
.
When you are using an index to optimize a GROUP BY, a fast full index scan solution will probably result in better throughput, while a index full scan solution will probably result in better response time. When you need to scan your Index Organized table, it is essential that you take advantage of the fast full index scan. Without the fast full index scan, you will be unable to use multi-block reads or exploit parallel query capabilities.
Note: Fast full scan is disabled by default, but it is possible to enable it in Oracle by setting FAST_FULL_SCAN_ENABLED to True. Make sure that you do not inadvertently try to scan Index Organized tables with fast full scans disabled.
The fast full index scan can provide a powerful alternative to the full table scan when the query references only columns in the index.
 .
.
DOMAIN INDEX
Retrieves one or more ROWIDs from a user-defined index.
DOMAIN INDEX is a user-defined index typically created on complex datatypes whose algorithms and optimizer characteristics are provided by the user. DOMAIN INDEXES are created using the Oracle Data Cartridge Interface API.
You can use the Oracle Explain Plan to derive user-defined CPU and I/O costs for domain indexes. The Oracle Explain plan displays these statistics in the OTHER column of PLAN_TABLE.
For example, assume table EMP has user-defined operator CONTAINS with a Domain Index EMP_RESUME on the resume column, and the index type of EMP_RESUME supports the operator CONTAINS.

Example

SELECT * FROM emp WHERE CONTAINS(resume, 'Oracle') = 1

Execution Plan

OPERATION
OPTIONS
OBJECT_NAME
OTHER
SELECT STATEMENT
TABLE ACCESS 
DOMAIN INDEX
 
BY ROWID
 
EMP
EMP_RESUME
 
CPU: 300, I/O: 4

UNDERSTANDING EXPLAIN PLAN


    Explain Plan a small overview


            To interpret an execution plan and correctly evaluate your SQL optimization options, you need to first understand the differences between the available database operations. The following topics describe each database access operation identified by the name given to it by the Oracle EXPLAIN PLAN command, along with its characteristics.
For each type of operation, an example is provided. In some cases, the example for an operation will use operations described later in the topic (such as MERGE JOIN, which always uses a SORT JOIN operation).
The operations are classified as row operations or set operations. The following list describes the differences between row and set operations. 


Row Operations
Set Operations
Executed on one row at a time
Executed on a result set of rows
Executed at the FETCH stage, if there is no set operation involved
Executed at the EXECUTE stage when the cursor is opened
Ability to view the first result before the last row is fetched
Inability to view the first result until all rows are fetched and processed
Example: A full-table scan
Example: A full-table scan with a GROUP BY



Aggregation Operations

The following Aggregation operations are available.

COUNT
Counts the rows in the result set to satisfy the COUNT() function

COUNT is executed when the RowNum pseudo-column is used without specifying a maximum value for RowNum. COUNT receives rows from its child operations and increments the RowNum counter. If a limiting counter is used on the RowNum pseudo-column, then the COUNT STOPKEY operation is used instead of COUNT
.

Example

.

select Name, City, State, RowNum from COMPANY where City > ‘Roanoke’order by Zip;
.
The query shown in the preceding listing selects rows from the COMPANY. Each row will have the original row number returned.

Execution Plan

SORT ORDER BY
COUNT
TABLE ACCESS BY ROWID COMPANY
INDEX RANGE SCAN COMPANY$CITY
 
Interpreting the Execution Plan
.
The Execution Plan shows that the index on the City column is used to find ROWIDs in the COMPANY table that satisfy the WHERE clause condition (where City > ‘Roanoke’). The ROWIDs from the City index scan are used to query the COMPANY table for the Name and State column values. For each row returned, the counter is incremented. Because of the use of the index, the rows that are returned will be the "lowest" city names that are greater than the value ‘Roanoke’. The rows will be returned from the COMPANY$CITY index in ascending order of the City column’s value. The RowNum pseudo-column will then be calculated and put into the row. The SORT ORDER BY operation will order the rows by Zip, as requested in the ORDER BY clause.  The RowNum values are assigned before the ordering takes place.
.
Counts the numbers of rows returned by a result set and stop processing when a certain number of rows are reached. This is usually the result of a WHERE clause which specifies a maximum ROWNUM (for example, WHERE ROWNUM <=10).

­­­Example 

.

 

Select Name, City, State from COMPANY where City > ‘Roanoke’ and Rownum <= 100;
.

Execution Plan

COUNT STOPKEY
TABLE ACCESS BY ROWID COMPANY
INDEX RANGE SCAN COMPANY$CITY



SORT
Performs a sort.

ORDER BY
Sorts a result set to satisfy an ORDER BY clause.

AGGREGATE
Occurs when a group function is used on data, which is already grouped.




SORT AGGREGATE is used to sort and aggregate result sets whenever a grouping function appears in a SQL statement without a GROUP BY clause. Grouping functions include MAX, MIN, COUNT, SUM, and AVG.

Example 

.

select SUM(Total) from SALES;
.

SORT AGGREGATE
TABLE ACCESS FULL SALES

.
The Execution Plan shows that after the SALES table is scanned (via the TABLE ACCESS FULL operation), the records are passed to the SORT AGGREGATE operation. SORT AGGREGATE sums the Total values and returns the output to the user.



JOIN
Sorts the rows in preparation for a merge join.
SORT JOIN sorts a set of records that is to be used in a MERGE JOIN operation.
Example
select C.Name  from COMPANY c, SALES s where C.Company_ID+0 = S.Company_ID+0
and S.Period_ID =3 and S.Sales_Total>1000;

Execution Plan

MERGE JOIN
SORT JOIN
TABLE ACCESS FULL SALES
SORT JOIN
TABLE ACCESS FULL COMPANY

Interpreting the Execution Plan

The Execution Plan shows that the COMPANY table and SALES table will be accessed using TABLE ACCESS FULL operations. Before the records from those tables are passed to the MERGE JOIN operation, they will first be processed by SORT JOIN operations that sort the records. The SORT JOIN output is used as input to the MERGE JOIN operation.

Jun 10, 2011

Convert a number to word

select to_char(to_date('1983','J'),'JSP') from dual;

In this query the number is converting into Julian date then by using fromat  'SP' to spell out

Example

  select to_char(sysdate,'DDSP'),to_char(sysdate,'MMSP'),to_char(sysdate,'YYYYSP') from dual  -- Spells the day ,month and the year

 In this only value upto 5373484 can be spelled  ; giving greater value will result in the following error

 ORA-01854: Julian date must be between 1 and 5373484

 select to_char(to_date('190000083','J'),'JSP') from dual;

 ORA-01830: date format picture ends before converting entire input string


Query to Spell  Rupee and Paise

select
TO_CHAR(TO_DATE(substr(10000.123,1,instr(10000.123,'.')-1),'J'),'JSP')||' RUPEES AND  '||
replace(replace(replace(replace(TO_CHAR(TO_DATE(substr(10000.123,instr(10000.123,'.')+1,length(10000.123)),'J'),'JSP'),'MILLION',''),'HUNDRED',''),'THOUSAND',''),'-',' ')  ||' PAISE ONLY' as number_char
from dual;


----------

Query to convert NUMBER to words

In Oracle 9i


SELECT  LEVEL+1 asnumber FROM dual WHERE to_char(to_date(LEVEL+1,'J'), 'JSP')  = 'ONE THOUSAND'
CONNECT BY to_char(to_date(LEVEL,'J'), 'JSP')  != 'ONE THOUSAND';

OR

SELECT  LEVEL FROM dual WHERE to_char(to_date(LEVEL,'J'), 'JSP')  = 'ONE THOUSAND ONE HUNDRED ELEVEN'
CONNECT BY to_char(to_date(LEVEL-1,'J'), 'JSP')  != 'ONE THOUSAND ONE HUNDRED ELEVEN'
AND LEVEL < 10001  -- Your get out of jail clause!;


In Oracle 10g

select sp, n from (select 'FIVE THOUSAND ONE' sp from dual)
   model dimension by (1 dim) measures (0 n, sp)  rules iterate (10000) until (to_char(date '2000-01-01' +
(ITERATION_NUMBER/86400),'SSSSSSP')=sp[1])  ( n[1]=ITERATION_NUMBER);



-------

May 19, 2011

ORA-20171: Workspace Error during BEGIN DDL

SQL > exec dbms_wm.beginddl('TABLE_NAME');

ORA-20171: WM error: 'CREATE TABLE' and 'CREATE SEQUENCE' privileges needed.


This error can be avoided by giving these below  grants to the particular user.

SQL > grant create TABLE  to username ;

SQL >  grant create SEQUENCE  to username;





Then execute the script ;it will be successful

SQL > exec dbms_wm.beginddl('TABLE_NAME');


--------

May 4, 2011

ORA-20104: cannot version disable this table

ORA-20104: cannot version disable this table
ORA-06512: at "SYS.LT", line 9152
ORA-06512: at line 3

the following error will occur if the TESTP table is a parent table and all the child table that refers TESTP is not versiondisabled .  






 An Example

create table TEST (ee number(10),fg varchar2(100)) ;

ALTER TABLE TEST ADD CONSTRAINT TEST_PK PRIMARY KEY (EE);

create table TESTP (ff number(10),ee number(10) ,constraint fk_fg foreign key(ee) references TEST(ee) );

ALTER TABLE TESTP ADD CONSTRAINT TESTp_PK PRIMARY KEY (ff);

execute dbms_wm.enableversioning('TEST');

execute dbms_wm.enableversioning('TESTP');

execute dbms_wm.disableversioning('TESTP');  This will result an error ( ORA-20104: cannot version disable this table )

to avoid this first you should disableversion child table  TEST and then parent table TESTP

execute dbms_wm.disableversioning('TEST');

execute dbms_wm.disableversioning('TESTP');