Sub topic 1
What an Oracle Execution Plan Is
An execution plan is the list of steps Oracle Database follows to run a SQL statement. Every slow query has one. Before you can tune a statement, you need to know what the plan is, who builds it, and why the plan you see may not be the plan that ran. This chapter builds that working model. Later chapters in this tutorial cover how to display and read plans in detail.
Prerequisites
This chapter assumes you:
- Write SQL with SELECT, joins, WHERE and GROUP BY.
- Know what tables, indexes and primary keys are.
- Can connect to an Oracle schema such as the HR sample schema, using SQL*Plus, SQL Developer or SQLcl.
- Have SELECT access to
V$SQLandV$PARAMETER, which the one query example below uses. You do not need these privileges to follow the reading.
SQL says what, the plan says how
SQL is declarative. You describe the rows you want, not the way to find them. This statement says nothing about indexes, join order, or whether to read the table in full:
SELECT e.last_name, d.department_name
FROM hr.employees e
JOIN hr.departments d ON d.department_id = e.department_id
WHERE e.salary > 10000;Oracle must decide those things itself. It could scan all of EMPLOYEES and look up each department. It could scan DEPARTMENTS first. It could use an index on SALARY if one exists, and it could join with nested loops or with a hash join. All of these return the same rows, but they can differ in run time by orders of magnitude. The execution plan records the single combination Oracle chose.
Where the plan comes from
When you submit a statement, Oracle passes it through several components. The ones that matter for plans are the parser, the optimizer and the row source generator.
The stages work as follows:
- The parser checks syntax and confirms that the objects and columns exist and that you have access to them.
- The query transformer may rewrite the statement into an equivalent form that is easier to optimize, for example by merging a view into the outer query.
- The estimator predicts how many rows each step will produce and what each step will cost.
- The plan generator builds candidate plans and keeps the one with the lowest estimated cost.
- The row source generator turns the chosen plan into an executable structure.
- The execution engine runs it.
The component that does the choosing is the cost-based optimizer, usually just called the optimizer. The plan is its output.
What the optimizer bases its choice on
The optimizer cannot try every plan against your data. It estimates. Its inputs are:
- Object statistics: row counts, block counts, distinct values per column, column histograms and index statistics, usually gathered by the automatic statistics job or by
DBMS_STATS. - System statistics: estimates of CPU speed and I/O performance.
- The statement itself: the predicates, the join conditions and any hints.
- Initialization parameters, such as
OPTIMIZER_MODEandOPTIMIZER_FEATURES_ENABLE. - Bind variable values, when Oracle peeks at them during the first hard parse.
From these inputs the optimizer computes two numbers that are central to everything you will read in a plan:
- Cardinality is the estimated number of rows an operation returns. It is derived from selectivity, the fraction of rows a predicate is expected to keep.
- Cost is a single unitless number that represents the estimated resources the plan will use, mainly I/O and CPU. Costs are only meaningful for comparing candidate plans for the same statement under the same conditions.
Cost is not time. A plan with cost 50 is not "faster than" a different statement's plan with cost 500. Even for one statement, a lower cost is only a prediction. If the cardinality estimates are wrong, the cost is wrong too. Most real tuning work comes down to finding where a cardinality estimate is wrong, which is why this tutorial spends time on it later.
You can check two of the parameters mentioned above with a query:
SELECT name, value
FROM v$parameter
WHERE name IN ('optimizer_mode', 'optimizer_features_enable');The default for OPTIMIZER_MODE is ALL_ROWS, which optimizes for returning the whole result set with the lowest total resource use. The alternative FIRST_ROWS_n favors returning the first n rows quickly.
A plan is a tree of operations
A plan is not a flat script. It is a tree. Each node is an operation, such as reading a table, looking up an index, joining two inputs or sorting. Oracle calls the data stream that an operation produces a row source. A child operation passes its rows up to its parent, and the parent combines or filters them.
For the example query above, a plan might have this shape. This is a simplified sketch, not output you should expect to match exactly:
- A hash join at the top.
- Under it, one child that reads
DEPARTMENTS. - Under it, another child that reads
EMPLOYEESand applies the salary filter.
The shape of the tree determines the order of execution. The order is not simply top to bottom. A later chapter shows the rule for reading it. For now, remember that the plan has two things you need to read: the operation each node performs and where it sits relative to its parent and siblings.
Estimated plan versus actual plan
There are two kinds of plan information, and mixing them up is a common source of wrong conclusions.
- The estimated plan is what the optimizer would choose if it parsed the statement now.
EXPLAIN PLANproduces it without running the statement. Its numbers, including row counts and cost, are all estimates. - The actual plan is the plan stored with a cursor that really executed, found in the shared pool. Oracle can also record runtime figures for it, such as the actual number of rows each step returned and the buffers it read.
The two can differ. EXPLAIN PLAN treats bind variables as unknown values of unknown type, so it may not reflect the peeked value used during the real parse. It does not take into account the session settings or the state that existed when the statement actually ran, and it can miss some adaptive behavior at run time. For routine checks, an estimated plan is fine. For diagnosing a statement that is slow in production, you want the actual plan with actual row counts. Later chapters cover both, starting with EXPLAIN PLAN and then DBMS_XPLAN.DISPLAY_CURSOR.
Why the plan for a statement can change
The same SQL text does not always get the same plan. Common reasons are:
- Statistics were regathered, or the data volume changed.
- An index was created, dropped or made invisible.
- A parameter such as
OPTIMIZER_FEATURES_ENABLEchanged, for example after a database upgrade. - A bind variable had a different value when the statement was last hard parsed, and the column has skewed data.
- The statement was aged out of the shared pool and parsed again.
A plan change is not automatically a problem. A new plan can be faster. What matters is that you can identify which plan ran, and compare it with another one.
Identifying a plan
Oracle gives each distinct SQL text a SQL_ID. Each distinct plan gets a PLAN_HASH_VALUE. If a statement's PLAN_HASH_VALUE changes between runs, its plan changed. The query below finds both for the earlier example:
SELECT sql_id, child_number, plan_hash_value, executions
FROM v$sql
WHERE sql_text LIKE 'SELECT e.last_name, d.department_name%'
AND sql_text NOT LIKE '%v$sql%';A statement can have several child cursors, each with its own plan. The pair of SQL_ID and CHILD_NUMBER identifies one specific cursor, and later chapters use that pair to display it.
Common misconceptions
| Belief | What is true |
|---|---|
| The plan with the lowest cost is the fastest. | Cost is an estimate. It is only as good as the statistics and cardinality estimates behind it. |
| Reading the plan top to bottom gives the execution order. | Execution order follows the tree. Children run before their parents, and the details come in a later chapter. |
| A full table scan is always bad. | For a query that reads a large share of a table, a full scan is often the cheapest choice. |
| `EXPLAIN PLAN` shows what ran. | It shows what the optimizer would choose at that moment, without running the statement. |
| A plan can be judged by its shape alone. | You also need row counts, predicates and, for tuning, the actual runtime figures. |
Exercises
Exercise
A colleague says "this query's plan has a cost of 12, so it must run faster than that other query, whose plan has a cost of 4000." What is wrong with this reasoning?
Show answer
Cost is a unitless estimate that is only comparable between candidate plans for the same statement under the same conditions. It does not measure time, and different statements are not comparable by it. It also depends on cardinality estimates, which may be wrong.
Exercise
Name two reasons why the plan from EXPLAIN PLAN might differ from the plan used when the statement actually ran, and name the column that lets you detect that a cursor's plan changed.
Show answer
EXPLAIN PLAN does not use the bind values that were peeked at the real hard parse, and it does not reflect the session or system state at that time (or later changes to statistics, indexes or parameters). PLANHASHVALUE in V$SQL changes when the plan changes.