this chapter discusses sql processing, optimization methods, and how the query optimizer (usually called the optimizer) chooses a specific plan to execute sql.
the chapter contains the following sections:
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i82005">overview of the query optimizer</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i82080">overview of optimizer access paths</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i51523">overview of joins</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i82029">reading and understanding execution plans</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#babdecgj">controlling optimizer behavior</a>
this section contains the following topics:
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i80683">optimizer operations</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#cihdfhbg">components of the query optimizer</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i79423">bind variable peeking</a>
<a></a>
note:
the optimizer might not make the same decisions from one version of oracle database to the next. in recent versions, the optimizer might make different decisions because better information is available.
when the user submits a sql statement for execution, the optimizer performs the following steps:
the optimizer generates a set of potential plans for the sql statement based on available access paths and hints.
the optimizer estimates the cost of each plan based on statistics in the data dictionary. statistics include information on the data distribution and storage characteristics of the tables, indexes, and partitions accessed by the statement.
serial plans with higher costs take longer to execute than those with smaller costs. when using a parallel plan, resource use is not directly related to elapsed time.
the optimizer compares the plans and chooses the plan with the lowest cost.
see also:
operation description
evaluation of expressions and conditions
the optimizer first evaluates expressions and conditions containing constants as fully as possible.
statement transformation
for complex statements involving, for example, correlated subqueries or views, the optimizer might transform the original statement into an equivalent join statement.
choice of optimizer goals
choice of access paths
choice of join orders
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/stats.htm#g49431">chapter 13, "managing optimizer statistics"</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/hintsref.htm#i8327">chapter 19, "using optimizer hints"</a>
the query optimizer operations include:
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i37745">query transformation</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i37746">estimation</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i37011">plan generation</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/img_text/pfgrf184.htm">description of "figure 11-1 optimizer components"</a>
each query portion of a statement is called a query block. the input to the query transformer is a parsed query, which is represented by a set of query blocks.
in the following example, the sql statement consists of two query blocks. the subquery in parentheses is the inner query block. theouter query block, which is the rest of the sql statement, retrieves names of employees in the departments whose ids were supplied by the subquery.
the query form determines how query blocks are interrelated. the transformer determines whether it is advantageous to rewrite the original sql statement into a semantically equivalent sql statement that can be processed more efficiently.
the query transformer employs several query transformation techniques, including the following:
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i55044">view merging</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i55050">predicate pushing</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i55054">subquery unnesting</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i55058">query rewrite with materialized views</a>
any combination of these transformations can apply to a given query.
each view referenced in a query is expanded by the parser into a separate query block. the block essentially represents the view definition, and thus the result of a view. one option for the optimizer is to analyze the view query block separately and generate a view subplan. the optimizer then processes the rest of the query by using the view subplan to generate an overall query plan. this technique usually leads to a suboptimal query plan because the view is optimized separately.
in view merging, the transformer merges the query block representing the view into the containing query block. for example, suppose you create a view as follows:
you then query the view as follows:
the optimizer can use view merging to transform the query of <code>employees_50_vw</code> into the following equivalent query:
the view merging optimization applies to views that contain only selections, projections, and joins. that is, mergeable views do not contain set operators, aggregate functions, <code>distinct</code>, <code>group by</code>, <code>connect by</code>, and so on.
to enable the optimizer to use view merging for any query issued by the user, you must grant the <code>merge</code> <code>any</code> <code>view</code> privilege to the user. grant the <code>merge</code> <code>view</code> privilege to a user on specific views to enable the optimizer to use view merging for queries on these views. these privileges are required only under specific conditions, such as when a view is not merged because the security checks fail.
in predicate pushing, the optimizer "pushes" the relevant predicates from the containing query block into the view query block. for views that are not merged, this technique improves the subplan of the unmerged view because the database can use the pushed-in predicates to access indexes or to use as filters.
for example, suppose you create a view that references two employee tables. the view is defined with a compound query that uses the<code>union</code> set operator, as follows:
because the view is a compound query, the optimizer cannot merge the view's query into the accessing query block. instead, the optimizer can transform the accessing statement by pushing its predicate, the <code>where</code> clause condition <code>department_id=50</code>, into the view's compound query. the equivalent transformed query is as follows:
in subquery unnesting, the optimizer transforms a nested query into an equivalent join statement, and then optimizes the join. this transformation enables the optimizer to take advantage of the join optimizer technique. the optimizer can perform this transformation only if the resulting join statement is guaranteed to return exactly the same rows as the original statement, and if subqueries do not contain aggregate functions such as <code>avg</code>.
for example, suppose you connect as user <code>sh</code> and execute the following query:
because the <code>customers.cust_id column</code> is a primary key, the optimizer can transform the complex query into the following join statement that is guaranteed to return the same data:
if the optimizer cannot transform a complex statement into a join statement, it selects execution plans for the parent statement and the subquery as though they were separate statements. the optimizer then executes the subquery and uses the rows returned to execute the parent query. to improve execution speed of the overall query plan, the optimizer orders the subplans efficiently.
a materialized view is like a query with a result that the database materializes and stores in a table. when the database finds a user query compatible with the query associated with a materialized view, then the database can rewrite the query in terms of the materialized view. this technique improves query execution because most of the query result has been precomputed.
the query transformer looks for any materialized views that are compatible with the user query and selects one or more materialized views to rewrite the user query. the use of materialized views to rewrite a query is cost-based. that is, the optimizer does not rewrite the query if the plan generated without the materialized views has a lower cost than the plan generated with the materialized views.
consider the following materialized view, <code>cal_month_sales_mv</code>, which aggregates the dollar amount sold each month:
assume that sales number is around one million in a typical month. the view has the precomputed aggregates for the dollar amount sold for each month. consider the following query, which asks for the sum of the amount sold for each month:
without query rewrite, the database must access <code>sales</code> directly and compute the sum of the amount sold. this method involves reading many million rows from <code>sales</code>, which invariably increases query response time. the join also further slows query response because the database must compute the join on several million rows. with query rewrite, the optimizer transparently rewrites the query as follows:
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i55109">selectivity</a>
this measure represents a fraction of rows from a row set. the selectivity is tied to a query predicate, such as <code>last_name='smith'</code>, or a combination of predicates.
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i55113">cardinality</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i55117">cost</a>
this measure represents units of work or resource used. the query optimizer uses disk i/o, cpu usage, and memory usage as units of work.
if statistics are available, then the estimator uses them to compute the measures. the statistics improve the degree of accuracy of the measures.
a predicate filters a specific number of rows from a row set. thus, the selectivity of a predicate indicates how many rows pass the predicate test. selectivity ranges from 0.0 to 1.0. a selectivity of 0.0 means that no rows are selected from a row set, whereas a selectivity of 1.0 means that all rows are selected. a predicate becomes more selective as the value approaches 0.0 and less selective (or more unselective) as the value approaches 1.0.
the optimizer estimates selectivity depending on whether statistics are available:
statistics not available
statistics available
when statistics are available, the estimator uses them to estimate selectivity. assume there are 150 distinct employee last names. for an equality predicate <code>last_name =</code> <code>'smith'</code>, selectivity is the reciprocal of the number <code>n</code> of distinct values of <code>last_name</code>, which in this example is .006 because the query selects rows that contain 1 out of 150 distinct values.
cardinality represents the number of rows in a row set. in this context, the row set can be a base table, a view, or the result of a join or<code>group</code> <code>by</code> operator.
the cost represents units of work or resource used in an operation. the optimizer uses disk i/o, cpu usage, and memory usage as units of work. the operation can be scanning a table, accessing rows from a table by using an index, joining two tables together, or sorting a row set. the cost is the number of work units expected to be incurred when the database executes the query and produces its result.
table scan or fast full index scan
index scan
the join cost represents the combination of the individual access costs of the two row sets being joined, plus the cost of the join operation.
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i51523">"overview of joins"</a>
a join order is the order in which different join items, such as tables, are accessed and joined together. assume that the database joins<code>table1</code>, <code>table2</code>, and <code>table3</code>. the join order might be as follows:
the database accesses <code>table1</code>.
the database accesses <code>table2</code> and joins its rows to <code>table1</code>.
the database accesses <code>table3</code> and joins its data to the result of the join between <code>table1</code> and <code>table2</code>.
the optimizer represents each nested subquery or unmerged view by a separate query block and generates a subplan. the database optimizes query blocks separately from the bottom up. thus, the database optimizes the innermost query block first and generates a subplan for it, and then lastly generates the outer query block representing the entire query.
the number of possible plans for a query block is proportional to the number of join items in the <code>from</code> clause. this number rises exponentially with the number of join items. for example, the possible plans for a join of five tables will be significantly higher than the possible plans for a join of two tables.
the plan generator uses an internal cutoff to reduce the number of plans it tries when finding the lowest-cost plan. the cutoff is based on the cost of the current best plan. if the current best cost is large, then the plan generator explores alternative plans to find a lower cost plan. if the current best cost is small, then the generator ends the search swiftly because further cost improvement will not be significant.
the cutoff works well if the plan generator starts with an initial join order that produces a plan with cost close to optimal. finding a good initial join order is a difficult problem.
in bind variable peeking (also known as bind peeking), the optimizer looks at the value in a bind variable when the database performs a hard parse of a statement.
when a query uses literals, the optimizer can use the literal values to find the best plan. however, when a query uses bind variables, the optimizer must select the best plan without the presence of literals in the sql text. this task can be extremely difficult. by peeking at bind values the optimizer can determine the selectivity of a <code>where</code> clause condition as if literals had been used, thereby improving the plan.
assume that the following 100,000 row <code>emp</code> table exists in the database. the table has the following definition:
the data is significantly skewed in the <code>deptno</code> column. the value 10 is found in 99.9% of the rows. each of the other <code>deptno</code> values (<code>0</code>through <code>9</code>) is found in 1% of the rows. you have gathered statistics for the table, resulting in a histogram on the <code>deptno</code> column. you define a bind variable and query <code>emp</code> using the bind value <code>9</code> as follows:
the query returns 10 rows:
to generate the execution plan for the query, the database peeked at the value <code>9</code> during the hard parse. the optimizer generated selectivity estimates as if the user had executed the following query:
when choosing a plan, the optimizer only peeks at the bind value during the hard parse. this plan may not be optimal for all possible values.
the adaptive cursor sharing feature enables a single statement that contains bind variables to use multiple execution plans. cursor sharing is "adaptive" because the cursor adapts its behavior so that the database does not always use the same plan for each execution or bind variable value.
for appropriate queries, the database monitors data accessed over time for different bind values, ensuring the optimal choice of cursor for a specific bind value. for example, the optimizer might choose one plan for bind value <code>9</code> and a different plan for bind value <code>10</code>. cursor sharing is "adaptive" because the cursor adapts its behavior so that the same plan is not always used for each execution or bind variable value.
adaptive cursor sharing is enabled for the database by default and cannot be disabled. note that adaptive cursor sharing does not apply to sql statements containing more than 14 bind variables.
a bind-sensitive cursor is a cursor whose optimal plan may depend on the value of a bind variable. the database monitors the behavior of a bind-sensitive cursor that uses different bind values to determine whether a different plan is beneficial.
the criteria used by the optimizer to decide whether a cursor is bind-sensitive include the following:
the optimizer has peeked at the bind values to generate selectivity estimates.
a histogram exists on the column containing the bind value.
the output is as follows:
the plan indicates that the optimizer chose an index range scan, which is expected because of the selectivity (only 1%) of the value <code>9</code>. you can query <code>v$sql</code> to view statistics about the cursor:
as shown in the following output, one child cursor exists for this statement and has been executed once. a small number of buffer gets are associated with the child cursor. because the <code>deptno</code> data is skewed, the database created a histogram. this histogram led the database to mark the cursor as bind-sensitive (<code>is_bind_sensitive</code> is <code>y</code>).
for each execution of the query with a new bind value, the database records the execution statistics for the new value and compares them to the execution statistics for the previous value. if execution statistics vary greatly, then the database marks the cursor bind-aware.
a bind-aware cursor is a bind-sensitive cursor eligible to use different plans for different bind values. after a cursor has been made bind-aware, the optimizer chooses plans for future executions based on the bind value and its selectivity estimate.
when a statement with a bind-sensitive cursor executes, the database decides whether to mark the cursor bind-aware. the decision depends on whether the cursor produces significantly different data access patterns for different bind values. if the database marks the cursor bind-aware, then the next time that the cursor executes the database does the following:
generates a new plan based on the new bind value.
marks the original cursor generated for the statement as not shareable (<code>v$sql.is_shareable</code> is <code>n</code>). this cursor is no longer usable and will be among the first to be aged out of the shared sql area.
because the cursor for this statement is bind-sensitive, the optimizer assumes that the cursor can be shared. consequently, the optimizer uses the same index range scan for the value <code>10</code> as for the value <code>9</code>.
the <code>v$sql</code> output shows that the same bind-sensitive cursor was executed a second time (the query using <code>10</code>) and required many more buffer gets than the first execution:
now you execute the query using the value <code>10</code> a second time. the database compares statistics for previous executions and marks the cursor as bind-aware. in this case, the optimizer decides that a new plan is warranted, so it performs a hard parse of the statement and generates a new plan. the new plan uses a full table scan instead of an index range scan:
a query of <code>v$sql</code> shows that the database created an additional child cursor (child number <code>1</code>) that represents the plan containing the full table scan. this new cursor shows a lower number of buffer gets and is marked bind-aware:
after you execute the query twice with value <code>10</code>, you execute it again using the more selective value <code>9</code>. because of adaptive cursor sharing, the optimizer "adapts" the cursor and chooses an index range scan rather than a full table scan for this value.
a query of <code>v$sql</code> indicates that the database created a new child cursor (child number <code>2</code>) for the execution of the query:
because the database is now using adaptive cursor sharing, the database no longer uses the original cursor (child <code>0</code>), which is not bind-aware. the shared sql area will age out the defunct cursor.
if the optimizer creates a plan for a bind-aware cursor, and if this plan is the same as an existing cursor, then the optimizer can performcursor merging. in this case, the database merges cursors to save space in the shared sql area. the database increases the selectivity range for the cursor to include the selectivity of the new bind.
suppose you execute a query with a bind value that does not fall within the selectivity ranges of the existing cursors. the database performs a hard parse and generates a new plan and new cursor. if this new plan is the same plan used by an existing cursor, then the database merges these two cursors and deletes one of the old cursors.
you can use the <code>v$</code> views for adaptive cursor sharing to see selectivity ranges, cursor information (such as whether a cursor is bind-aware or bind-sensitive), and execution statistics:
<code>v$sql</code> shows whether a cursor is bind-sensitive or bind-aware
<code>v$sql_cs_histogram</code> shows the distribution of the execution count across a three-bucket execution history histogram
<code>v$sql_cs_selectivity</code> shows the selectivity ranges stored for every predicate containing a bind variable if the selectivity was used to check cursor sharing
<code>v$sql_cs_statistics</code> summarizes the information that the optimizer uses to determine whether to mark a cursor bind-aware.
access paths are ways in which data is retrieved from the database. in general, index access paths are useful for statements that retrieve a small subset of table rows, whereas full scans are more efficient when accessing a large portion of the table. online transaction processing (oltp) applications, which consist of short-running sql statements with high selectivity, often are characterized by the use of index access paths. decision support systems, however, tend to use partitioned tables and perform full scans of the relevant partitions.
this section describes the data access paths that the database can use to locate and retrieve any row in any table.
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i44851">full table scans</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i44963">rowid scans</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i52300">index scans</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i51070">cluster access</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i51075">hash access</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i79194">sample table scans</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i36043">how the query optimizer chooses an access path</a>
full table scans are cheaper than index range scans when accessing a large fraction of the blocks in a table. full table scans can use larger i/o calls, and making fewer large i/o calls is cheaper than making many smaller calls.
the optimizer uses a full table scan in any of the following cases:
if the query cannot use existing indexes, then it uses a full table scan. for example, if there is a function used on the indexed column in the query, then the optimizer cannot use the index and instead uses a full table scan.
if the optimizer thinks that the query requires most of the blocks in the table, then it uses a full table scan, even though indexes are available.
if a table contains less than <code>db_file_multiblock_read_count</code> blocks under the high water mark, which the database can read in a single i/o call, then a full table scan might be cheaper than an index range scan, regardless of the fraction of tables being accessed or indexes present.
a high degree of parallelism for a table skews the optimizer toward full table scans over range scans. examine the <code>degree</code> column in<code>all_tables</code> for the table to determine the degree of parallelism.
you can use the <code>cache</code> and <code>nocache</code> hints to indicate where the retrieved blocks are placed in the buffer cache. the <code>cache</code> hint instructs the optimizer to place the retrieved blocks at the most recently used end of the lru list in the buffer cache when the database performs a full table scan.
table size size criteria caching
small
number of blocks < 20 or 2% of total cached blocks, whichever is larger
if <code>statistics_level</code> is se to <code>typical</code> or higher, then oracle database decides whether to cache a table depending on the table scan history. the database caches the table only if a future table scan is likely to find the cached blocks. if <code>statistics_level</code> is set to <code>basic</code>, then the table is not cached.
medium
larger than a small table, but < 10% of total cached blocks
oracle database decides whether to cache a table based on its table scan and workload history. it caches the table only if a future table scan is likely to find the cached blocks.
large
> 10% of total cached blocks
not cached
automatic caching of small tables is disabled for tables that are created or altered with the <code>cache</code> attribute.
when a full table scan is required, the database can improve response time by using multiple parallel execution servers. in some cases, as when the database has a large amount of memory, the database can cache parallel query data in the sga instead of using direct reads into the pga. typically, parallel queries occur in low-concurrency data warehouses because of the potential resource usage.
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e25554/toc.htm">oracle database data warehousing guide</a>
to access a table by rowid, oracle database first obtains the rowids of the selected rows, either from the statement's <code>where</code> clause or through an index scan of one or more of the table's indexes. oracle database then locates each selected row in the table based on its rowid.
this is generally the second step after retrieving the rowid from an index. the table access might be required for any columns in the statement not present in the index.
access by rowid does not need to follow every index scan. if the index contains all the columns needed for the statement, then table access by rowid might not occur.
in this method, a row is retrieved by traversing the index, using the indexed column values specified by the statement. an index scan retrieves data from an index based on the value of one or more columns in the index. to perform an index scan, oracle database searches the index for the indexed column values accessed by the statement. if the statement accesses only columns of the index, then oracle database reads the indexed column values directly from the index, rather than from the table.
the index contains not only the indexed value, but also the rowids of rows in the table having that value. therefore, if the statement accesses other columns in addition to the indexed columns, then oracle database can find the rows in the table by using either a table access by rowid or a cluster scan.
an index scan can be one of the following types:
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i82433">assessing i/o for blocks, not rows</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i44986">index unique scans</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i45075">index range scans</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i45191">index range scans descending</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i51571">index skip scans</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i82107">full scans</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i52044">fast full index scans</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i56068">index joins</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i82117">bitmap indexes</a>
oracle database performs i/o by blocks. therefore, the optimizer's decision to use full table scans is influenced by the percentage of blocks accessed, not rows. this is called the index clustering factor. if blocks contain single rows, then rows accessed and blocks accessed are the same.
however, most tables have multiple rows in each block. consequently, the desired number of rows may be clustered in a few blocks or spread out over a larger number of blocks.
assume the following situation:
there is a table with 9 rows.
there is a non-unique index on <code>col1</code> for table.
the <code>c1</code> column currently stores the values <code>a</code>, <code>b</code>, and <code>c</code>.
the table only has three data blocks.
case 1: the index clustering factor is low for the rows as they are arranged in the following diagram.
this is because the rows that have the same indexed column values for <code>c1</code> are located within the same physical blocks in the table. the cost of using a range scan to return all rows that have the value <code>a</code> is low because only one block in the table must be read.
case 2: if the same rows in the table are rearranged so that the index values are scattered across the table blocks (rather than collocated), then the index clustering factor is higher.
this is because all three blocks in the table must be read in order to retrieve all rows with the value <code>a</code> in <code>col1</code>.
this scan returns, at most, a single rowid. oracle database performs a unique scan if a statement contains a <code>unique</code> or a <code>primary</code> <code>key</code>constraint that guarantees that only a single row is accessed.
the database uses this access path when the user specifies all columns of a unique (b-tree) index or an index created as a result of a primary key constraint with equality conditions.
in general, you should not need to use a hint to do a unique scan. there might be cases where the table is across a database link and being accessed from a local table, or where the table is small enough for the optimizer to prefer a full table scan.
an index range scan is a common operation for accessing selective data. it can be bounded (bounded on both sides) or unbounded (on one or both sides). data is returned in the ascending order of index columns. multiple rows with identical values are sorted in ascending order by rowid.
if you require the data to be sorted by order, then use the <code>order</code> <code>by</code> clause, and do not rely on an index. if an index can satisfy an <code>order</code> <code>by</code>clause, then the optimizer uses this option and avoids a sort.
this should be a highly selective query, and you should see the query using the index on the column to retrieve the desired rows. the data returned is sorted in ascending order by the rowids for the <code>order_date</code>. because the index column <code>order_date</code> is identical for the selected rows here, the data is sorted by rowid.
the optimizer uses a range scan when it finds one or more leading columns of an index specified in conditions, such as the following:
<code>col1 = :b1</code>
<code>col1 < :b1</code>
<code>col1 > :b1</code>
<code>and</code> combination of the preceding conditions for leading columns in the index
<code>col1 like 'asd%'</code> wild-card searches should not be in a leading position otherwise the condition <code>col1 like '%asd'</code> does not result in a range scan
range scans can use unique or non-unique indexes. range scans avoid sorting when index columns constitute the <code>order</code> <code>by</code>/<code>group</code> <code>by</code>clause.
an index range scan descending is identical to an index range scan, except that the data is returned in descending order. indexes, by default, are stored in ascending order. usually, the database uses this scan when ordering data in a descending order to return the most recent data first, or when seeking a value less than a specified value.
the optimizer uses index range scan descending when an index can satisfy an order by descending clause.
index skip scans improve index scans by nonprefix columns. often, scanning index blocks is faster than scanning table data blocks.
skip scanning lets a composite index be split logically into smaller subindexes. in skip scanning, the initial column of the composite index is not specified in the query. in other words, it is skipped.
the database determines the number of logical subindexes by the number of distinct values in the initial column. skip scanning is advantageous when there are few distinct values in the leading column of the composite index and many distinct values in the nonleading key of the index.
the database may choose an index skip scan when the leading column of the composite index is not specified in a query predicate. for example, assume that you run the following query for a customer in the <code>sh.customers</code> table:
the <code>customers</code> table has a column <code>cust_gender</code> whose values are either <code>m</code> or <code>f</code>. assume that a composite index exists on the columns (<code>cust_gender</code>, <code>cust_email</code>) that was created as follows:
the database can use a skip scan of this index even though <code>cust_gender</code> is not specified in the <code>where</code> clause.
when searching for the record for the customer whose email is <code>[email protected]</code>, the database searches the subindex with the value <code>f</code>first and then searches the subindex with the value <code>m</code>. conceptually, the database processes the query as follows:
a full index scan eliminates a sort operation, because the data is ordered by the index key. it reads the blocks singly. oracle database may use a full scan in any of the following situations:
an <code>order</code> <code>by</code> clause that meets the following requirements is present in the query:
all of the columns in the <code>order</code> <code>by</code> clause must be in the index.
the order of the columns in the <code>order</code> <code>by</code> clause must match the order of the leading index columns.
the <code>order</code> <code>by</code> clause can contain all of the columns in the index or a subset of the columns in the index.
the query requires a sort merge join. the database can perform a full index scan instead of doing a full table scan followed by a sort when the query meets the following requirements:
all of the columns referenced in the query must be in the index.
the order of the columns referenced in the query must match the order of the leading index columns.
the query can contain all of the columns in the index or a subset of the columns in the index.
a <code>group</code> <code>by</code> clause is present in the query, and the columns in the <code>group</code> <code>by</code> clause are present in the index. the columns do not need to be in the same order in the index and the <code>group</code> <code>by</code> clause. the <code>group</code> <code>by</code> clause can contain all of the columns in the index or a subset of the columns in the index.
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i49183">"sort merge joins"</a>
fast full index scans are an alternative to a full table scan when the index contains all the columns that are needed for the query, and at least one column in the index key has the <code>not</code> <code>null</code> constraint. a fast full scan accesses the data in the index itself, without accessing the table. the database cannot use this scan to eliminate a sort operation because the data is not ordered by the index key. the database reads the entire index using multiblock reads, unlike a full index scan, and can scan in parallel.
setting <code>parallel</code> for indexes does not impact the cost calculation.
bitmap indexes and bitmap join indexes are available only in the oracle enterprise edition.
the available access paths for the statement
the estimated cost of executing the statement, using each access path or combination of paths
to choose an access path, the optimizer first determines which access paths are available by examining the conditions in the statement's<code>where</code> clause and its <code>from</code> clause. the optimizer then generates a set of possible execution plans using available access paths and estimates the cost of each plan, using the statistics for the index, columns, and tables accessible to the statement. finally, the optimizer chooses the execution plan with the lowest estimated cost.
when choosing an access path, the query optimizer is influenced by the following:
you can instruct the optimizer to use a specific access path using a hint, except when the statement's <code>from</code> clause contains <code>sample</code> or<code>sample</code> <code>block</code>.
old statistics
for example, if a table has not been analyzed since it was created, and if it has less than <code>db_file_multiblock_read_count</code> blocks under the high water mark, then the optimizer thinks that the table is small and uses a full table scan. review the <code>last_analyzed</code> and<code>blocks</code> columns in the <code>all_tables</code> table to examine the statistics.
joins are statements that retrieve data from multiple tables. a join is characterized by multiple tables in the <code>from</code> clause. the existence of a join condition in the <code>where</code> clause defines the relationship between the tables. in a join, one row set is called inner, and the other is called outer.
this section discusses:
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i36235">how the query optimizer executes join statements</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i76330">how the query optimizer chooses execution plans for joins</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i49732">nested loop joins</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i76073">hash joins</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i49183">sort merge joins</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#babdgfie">cartesian joins</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i50026">outer joins</a>
access paths
as for simple statements, the optimizer must choose an access path to retrieve data from each table in the join statement.
join method
to join each pair of row sources, oracle database must perform a join operation. join methods include nested loop, sort merge, cartesian, and hash joins.
join order
to execute a statement that joins more than two tables, oracle database joins two of the tables and then joins the resulting row source to the next table. this process continues until all tables are joined into the result.
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i82080">"overview of optimizer access paths"</a>
the query optimizer considers the following when choosing an execution plan:
the optimizer first determines whether joining two or more tables definitely results in a row source containing at most one row. the optimizer recognizes such situations based on <code>unique</code> and <code>primary</code> <code>key</code> constraints on the tables. if such a situation exists, then the optimizer places these tables first in the join order. the optimizer then optimizes the join of the remaining set of tables.
with the query optimizer, the optimizer generates a set of execution plans, according to possible join orders, join methods, and available access paths. the optimizer then estimates the cost of each plan and chooses the one with the lowest cost. the optimizer estimates costs in the following ways:
the optimizer also considers other factors when determining the cost of each operation. for example:
you can use the <code>ordered</code> hint to override the optimizer's choice of join orders. if the <code>ordered</code> hint specifies a join order that violates the rule for an outer join, then the optimizer ignores the hint and chooses the order. also, you can override the optimizer's choice of join method with hints.
the database joins small subsets of data.
the join condition is an efficient method of accessing the second table.
it is important to ensure that the inner table is driven from (dependent on) the outer table. if the inner table's access path is independent of the outer table, then the same rows are retrieved for every iteration of the outer loop, degrading performance considerably. in such cases, hash joins joining the two independent row sources perform better.
a nested loop join involves the following steps:
the optimizer determines the driving table and designates it as the outer table.
the other table is designated as the inner table.
for every row in the outer table, oracle database accesses all the rows in the inner table. the outer loop is for every row in the outer table and the inner loop is for every row in the inner table. the outer loop appears before the inner loop in the execution plan, as follows:
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#babdgfie">"cartesian joins"</a>
oracle database 11g introduces a new implementation for nested loop joins. as a result, execution plans that include nested loops might appear different than they did in previous releases of oracle database. both the new implementation and the original implementation for nested loop joins are possible in oracle database 11g. so, when analyzing execution plans, it is important to understand that the number of<code>nested</code> <code>loops</code> join row sources might be different.
consider the following query:
before oracle database 11g, the execution plan for this query might appear similar to the following execution plan:
in this example, the outer side of the join consists of a scan of the <code>hr.departments</code> table that returns the rows that match the condition<code>department_name</code> <code>in</code> <code>('marketing', 'sales')</code>. the inner loop retrieves the employees in the <code>hr.employees</code> table that are associated with those departments.
oracle database 11g introduces a new implementation for nested loop joins to reduce overall latency for physical i/o. when an index or a table block is not in the buffer cache and is needed to process the join, a physical i/o is required. oracle database 11g can batch multiple physical i/o requests and process them using a vector i/o instead of processing them one at a time.
as part of the new implementation for nested loop joins, two <code>nested</code> <code>loops</code> join row sources might appear in the execution plan where only one would have appeared in prior releases. in such cases, oracle database allocates one <code>nested</code> <code>loops</code> join row source to join the values from the table on the outer side of the join with the index on the inner side. a second row source is allocated to join the result of the first join, which includes the rowids stored in the index, with the table on the inner side of the join.
in this case, the rows from the <code>hr.departments</code> table constitute the outer side of the first join. the inner side of the first join is the index<code>emp_department_ix</code>. the results of the first join constitute the outer side of the second join, which has the <code>hr.employees</code> table as its inner side.
there are cases where a second join row source is not allocated, and the execution plan looks the same as it did in prior releases. the following list describes such cases:
all of the columns needed from the inner side of the join are present in the index, and there is no table access required. in this case, oracle database allocates only one join row source.
the order of the rows returned might be different than it was in previous releases. hence, when oracle database tries to preserve a specific ordering of the rows, for example to eliminate the need for an <code>order</code> <code>by</code> sort, oracle database might use the original implementation for nested loop joins.
the <code>optimizer_features_enable</code> initialization parameter is set to a release before oracle database 11g. in this case, oracle database uses the original implementation for nested loop joins.
the optimizer uses nested loop joins when joining small number of rows, with a good driving condition between the two tables. you drive from the outer loop to the inner loop, so the order of tables in the execution plan is important.
the outer loop is the driving row source. it produces a set of rows for driving the join condition. the row source can be a table accessed using an index scan or a full table scan. also, the rows can be produced from any other operation. for example, the output from a nested loop join can serve as a row source for another nested loop join.
the inner loop is iterated for every row returned from the outer loop, ideally by an index scan. if the access path for the inner loop is not dependent on the outer loop, then you can end up with a cartesian product; for every iteration of the outer loop, the inner loop produces the same set of rows. therefore, you should use other join methods when two independent row sources are joined together.
if the optimizer chooses to use some other join method, then you can use the <code>use_nl</code>(<code>table1 table2</code>) hint, where <code>table1</code> and <code>table2</code> are the aliases of the tables being joined.
the outer loop of a nested loop can be a nested loop itself. you can nest two or more outer loops to join as many tables as needed. each loop is a data access method, as follows:
this method is best when the smaller table fits in available memory. the cost is then limited to a single read pass over the data for the two tables.
the optimizer uses a hash join to join two tables if they are joined using an equijoin and if either of the following conditions are true:
a large amount of data must be joined.
a large fraction of a small table must be joined.
the row sources are sorted already.
a sort operation does not have to be done.
however, if a sort merge join involves choosing a slower access method (an index scan as opposed to a full table scan), then the benefit of using a sort merge might be lost.
sort merge joins are useful when the join condition between two tables is an inequality condition such as <code><</code>, <code><=</code>, <code>></code>, or <code>>=</code>. sort merge joins perform better than nested loop joins for large data sets. you cannot use hash joins unless there is an equality condition.
in a merge join, there is no concept of a driving table. the join consists of two steps:
sort join operation: both the inputs are sorted on the join key.
merge join operation: the sorted lists are merged together.
if the input is sorted by the join column, then a sort join operation is not performed for that row source. however, a sort merge join always creates a positionable sort buffer for the right side of the join so that it can seek back to the last match in the case where duplicate join key values come out of the left side of the join.
the optimizer can choose a sort merge join over a hash join for joining large amounts of data if any of the following conditions are true:
the join condition between two tables is not an equijoin.
because of sorts required by other operations, the optimizer finds it is cheaper to use a sort merge than a hash join.
to instruct the optimizer to use a sort merge join, apply the <code>use_merge</code> hint. you might also need to give hints to force an access path.
there are situations where it makes sense to override the optimizer with the <code>use_merge</code> hint. for example, the optimizer can choose a full scan on a table and avoid a sort operation in a query. however, there is an increased cost because a large table is accessed through an index and single block reads, as opposed to faster access through a full table scan.
the optimizer uses cartesian joins when it is asked to join two tables with no join conditions. in some cases, a common filter condition between the two tables could be picked up by the optimizer as a possible join condition. in other cases, the optimizer may decide to generate a cartesian product of two very small tables that are both joined to the same large table.
applying the <code>ordered</code> hint, instructs the optimizer to use a cartesian join. by specifying a table before its join table is specified, the optimizer does a cartesian join.
the database uses this operation to loop through an outer join between two tables. the outer join returns the outer (preserved) table rows, even when no corresponding rows are in the inner (optional) table.
in a regular outer join, the optimizer chooses the order of tables (driving and driven) based on the cost. however, in a nested loop outer join, the join condition determines the order of tables. the database uses the outer table, with rows that are being preserved, to drive to the inner table.
the optimizer uses nested loop joins to process an outer join in the following circumstances:
it is possible to drive from the outer table to inner table.
data volume is low enough to make the nested loop method efficient.
the optimizer uses hash joins for processing an outer join in the following cases:
the data volume is large enough to make the hash join method efficient.
it is not possible to drive from the outer table to the inner table.
the order of tables is determined by cost. the outer table, including preserved rows, may be used to build the hash table, or it may be used to probe one.
the query looks for customers which satisfy various conditions. an outer join returns <code>null</code> for the inner table columns along with the outer (preserved) table rows when it does not find any corresponding rows in the inner table. this operation finds all the <code>customers</code> rows that do not have any <code>orders</code> rows.
in this case, the outer join condition is the following:
the components of this condition represent the following:
the outer table is <code>customers</code>.
the inner table is <code>orders</code>.
the join preserves the <code>customers</code> rows, including those rows without a corresponding row in <code>orders</code>.
you could use a <code>not</code> <code>exists</code> subquery to return the rows. however, because you are querying all the rows in the table, the hash join performs better (unless the <code>not</code> <code>exists</code> subquery is not nested).
the view definition is as follows:
when an outer join cannot drive from the outer (preserved) table to the inner (optional) table, it cannot use a hash join or nested loop joins. then it uses the sort merge outer join for performing the join operation.
the optimizer uses sort merge for an outer join:
if a nested loop join is inefficient. a nested loop join can be inefficient because of data volumes.
the optimizer finds it is cheaper to use a sort merge over a hash join because of sorts required by other operations.
any employees without departments
any departments without employees
the statement produces the following output:
notice that <code>hash</code> <code>join</code> <code>full</code> <code>outer</code> is included in the plan. therefore, the query uses the hash full outer join execution method. typically, when the full outer join condition between two tables is an equi-join, the hash full outer join execution method is possible, and oracle database uses it automatically.
to instruct the optimizer to consider using the hash full outer join execution method, apply the <code>native_full_outer_join</code> hint. to instruct the optimizer not to consider using the hash full outer join execution method, apply the <code>no_native_full_outer_join</code> hint. the<code>no_native_full_outer_join</code> hint instructs the optimizer to exclude the native execution method when joining each specified table. instead, the full outer join is executed as a union of left outer join and an anti-join.
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/ex_plan.htm#g42231">chapter 12, "using explain plan"</a>
notes:
the steps in the <code>explain</code> <code>plan</code> output in this chapter may be different on your system. the optimizer may choose different execution plans, depending on database configurations.
each row in the output table corresponds to a single step in the execution plan. note that the step ids with asterisks are listed in the predicate information section.
the numbering of the step ids reflects the order in which they are displayed in response to the <code>explain</code> <code>plan</code> statement. each step of the execution plan either retrieves rows from the database or accepts rows from one or more row sources as input.
step 3 reads all rows of the <code>employees</code> table.
step 5 looks up each <code>job_id</code> in <code>job_id_pk</code> index and finds the rowids of the associated rows in the <code>jobs</code> table.
step 4 retrieves the rows with rowids that were returned by step 5 from the <code>jobs</code> table.
step 7 looks up each <code>department_id</code> in <code>dept_id_pk</code> index and finds the rowids of the associated rows in the <code>departments</code>table.
step 6 retrieves the rows with rowids that were returned by step 7 from the <code>departments</code> table.
step 2 performs the nested loop operation on <code>job_id</code> in the <code>jobs</code> and <code>employees</code> tables, accepting row sources from steps 3 and 4, joining each row from step 3 source to its corresponding row in step 4, and returning the resulting rows to step 2.
step 1 performs the nested loop operation, accepting row sources from step 2 and step 6, joining each row from step 2 source to its corresponding row in step 6, and returning the resulting rows to step 1.
initialization parameter description
converts literal values in sql statements to bind variables. converting the values improves cursor sharing and can affect the execution plans of sql statements. the optimizer generates the execution plan based on the presence of the bind variables and not the actual literal values.
specifies the number of blocks that are read in a single i/o during a full table scan or index fast full scan. the optimizer uses the value of<code>db_file_multiblock_read_count</code> to cost full table scans and index fast full scans. larger values result in a cheaper cost for full table scans and can result in the optimizer choosing a full table scan over an index scan. if this parameter is not set explicitly (or is set is 0), then the default value corresponds to the maximum i/o size that can be efficiently performed and is platform-dependent.
controls the costing of an index probe in conjunction with a nested loop. the range of values <code>0</code> to <code>100</code> indicates percentage of index blocks in the buffer cache, which modifies the optimizer's assumptions about index caching for nested loops and in-list iterators. a value of <code>100</code> infers that 100% of the index blocks are likely to be found in the buffer cache and the optimizer adjusts the cost of an index probe or nested loop accordingly. use caution when using this parameter because execution plans can change in favor of index caching.
adjusts the cost of index probes. the range of values is 1 to 10000. the default value is 100, which means that indexes are evaluated as an access path based on the normal costing model. a value of 10 means that the cost of an index access path is one-tenth the normal cost of an index access path.
controls the amount of memory allocated for sorts and hash joins. larger amounts of memory allocated for sorts or hash joins reduce the optimizer cost of these operations.
enables the optimizer to cost a star transformation for star queries (if <code>true</code>). the star transformation combines the bitmap indexes on the various fact table columns.
you can use this parameter to preserve the old behavior of the optimizer after a database upgrade. for example, if you upgrade the oracle database 11g from release 1 (11.1.0.7) to release 2 (11.2.0.2), then the default value of the <code>optimizer_features_enable</code> parameter changes from <code>11.1.0.7</code> to <code>11.2.0.2</code>. this upgrade results in the optimizer enabling optimization features based on 11.2.0.2.
for backward compatibility, you might not want the query plans to change because of new optimizer features in a new release. in such a case, you can set the <code>optimizer_features_enable</code> parameter to an earlier version.
to set optimizer_features_enable:
query the current optimizer features settings.
for example, run the following sql*plus command:
set the optimizer features setting at the instance or session level.
for example, run the following sql statement to set the optimizer version to 10.2.0.5:
the preceding statement disables all new optimizer features that were added in releases following release 10.2.0.5. if you upgrade to a new release and you want to enable the features available with that release, then you do not need to explicitly set the<code>optimizer_features_enable</code> initialization parameter.
best throughput (default)
the database uses the least amount of resources necessary to process all rows accessed by the statement.
for applications performed in batch, such as oracle reports applications, optimize for best throughput. usually, throughput is more important in batch applications, because the user initiating the application is only concerned with the time necessary for the application to complete. response time is less important because the user does not examine the results of individual statements while the application is running.
best response time
the database uses the least amount of resources necessary to process the first row accessed by a sql statement.
for interactive applications such as oracle forms applications or sql*plus queries, optimize for best response time. usually, response time is important in interactive applications because the interactive user is waiting to see the first row or first few rows accessed by the statement.
the optimizer behavior when choosing an optimization approach and goal for a sql statement is affected by the following factors:
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i38217">setting the optimizer_mode initialization parameter</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i74078">using hints to change the optimizer goal</a>
<a href="http://docs.oracle.com/cd/e11882_01/server.112/e16638/optimops.htm#i50787">optimizer statistics in the data dictionary</a>
value description
<code>all_rows</code>
<code>first_rows_</code><code>n</code>
the optimizer uses a cost-based approach, regardless of the presence of statistics, and optimizes with a goal of best response time to return the first n number of rows, where n equals 1, 10, 100, or 1000.
<code>first_rows</code>
note that using heuristics sometimes leads the optimizer to generate a plan with a cost that is significantly larger than the cost of a plan without applying the heuristic. <code>first_rows</code> is available for backward compatibility and plan stability; use <code>first_rows_</code><code>n</code> instead.
the following statement in an initialization parameter file establishes the goal of the query optimizer for all sessions of the instance to best response time:
the following sql statement changes the goal of the query optimizer for the current session to best response time:
if the optimizer uses the cost-based approach for a sql statement, and if some tables accessed by the statement have no statistics, then the optimizer uses internal information, such as the number of data blocks allocated to these tables, to estimate other statistics for these tables.
hint description
this hint instructs oracle database to optimize an individual sql statement with a goal of best response time to return the first n number of rows, where n equals any positive integer. the hint uses a cost-based approach for the sql statement, regardless of the presence of statistic.
this hint explicitly chooses the cost-based approach to optimize a sql statement with a goal of best throughput.
to maintain the effectiveness of the query optimizer, you must have statistics that are representative of the data. for table columns that contain values with large variations in number of duplicates, called skewed data, you should collect histograms.
the resulting statistics provide the query optimizer with information about data uniqueness and distribution. using this information, the query optimizer is able to compute plan costs with a high degree of accuracy and choose the best execution plan based on the least cost.
starting in oracle database 11g release 2 (11.2.0.4), the <code>optimizer_dynamic_sampling</code> initialization parameter has an <code>11</code> setting that enables the optimizer to gather dynamic statistics whenever it deems them necessary. for example, the optimizer can gather dynamic statistics for table scans, index access, joins, and <code>group by</code> operations, thus improving the quality of optimizer decisions.
如有錯誤,歡迎指正
作者:czmmiao 文章出處:http://czmmiao.iteye.com/blog/2086507