Sub topic 9
Why EXPLAIN PLAN may not show the real plan
This chapter assumes you can run EXPLAIN PLAN and DBMS_XPLAN.DISPLAY, and that you can read the basic columns of a plan table. It also assumes you know what a bind variable is. The goal is to learn when an estimated plan can be trusted and when you need the plan of a cursor that actually ran.
What EXPLAIN PLAN does
EXPLAIN PLAN asks the optimizer to parse a statement and write the plan it would choose into PLAN_TABLE. It does not execute the statement. It also does not create a cursor in the shared pool that the application could reuse. Nothing you see is a record of what happened. It is a prediction made at one moment, in one session, with one set of inputs.
The real plan comes from a separate parse, usually in another session and often at another time. If any input differs between the two parses, the plans can differ. The diagram groups those inputs.
Bind variables
Bind variables are the most common cause of a mismatch. EXPLAIN PLAN does not peek at bind values. It also treats each bind variable as a VARCHAR2, whatever type the application will supply.
When the optimizer parses a real statement for the first time, it can peek at the bind values. This is called bind peeking. It uses the peeked values with column histograms to estimate how many rows will match. EXPLAIN PLAN has no peeked value, so it falls back to a generic selectivity guess. On a skewed column, the real plan and the estimated plan can be quite different.
The type matters as well. Suppose a VARCHAR2 column such as ACCOUNT_CODE holds digits, and the application binds a NUMBER. Oracle must convert the column, not the bind, so the real predicate becomes TO_NUMBER("ACCOUNT_CODE")=:B1. That conversion blocks a normal index on the column. EXPLAIN PLAN assumes a VARCHAR2 bind, needs no conversion, and happily shows an index range scan. The estimated plan looks efficient while the real one does a full scan.
You can check how a statement really ran by running it with a bind and displaying its cursor. In SQL*Plus:
VARIABLE dept NUMBER
EXEC :dept := 50
SELECT /*+ GATHER_PLAN_STATISTICS */ last_name
FROM hr.employees
WHERE department_id = :dept;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(
format => 'ALLSTATS LAST +PEEKED_BINDS'));The +PEEKED_BINDS modifier adds a section that lists the bind values the optimizer used when it built the plan. If you need to judge a plan, that section tells you which value the plan was built for.
Session settings
The optimizer reads many parameters from the session that parses the statement. Examples are optimizer_mode, optimizer_features_enable, optimizer_index_cost_adj, db_file_multiblock_read_count and cursor_sharing. NLS settings can also change the plan, because they affect sort order and implicit conversions.
Your tuning session often has different settings from the application session. This can happen when the application sets parameters at login, or when a logon trigger does. Here is a simple demonstration of the effect:
ALTER SESSION SET optimizer_mode = FIRST_ROWS_1;
EXPLAIN PLAN FOR
SELECT e.last_name, d.department_name
FROM hr.employees e
JOIN hr.departments d ON d.department_id = e.department_id
ORDER BY e.last_name;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY(format => 'BASIC +NOTE'));
ALTER SESSION SET optimizer_mode = ALL_ROWS;The plan produced under FIRST_ROWS_1 favors operations that return the first row quickly, such as nested loops. If the application ran under ALL_ROWS, it may use a hash join. The EXPLAIN PLAN output would then describe a plan that the application never uses.
Statistics and cursor age
A cursor in the shared pool keeps the plan it was built with. If you gather new statistics, Oracle usually invalidates dependent cursors, but not always right away. The default NO_INVALIDATE behavior of the statistics-gathering procedures spreads out the invalidation over a period of time. Until a cursor is invalidated and reparsed, the application keeps using the old plan.
Your EXPLAIN PLAN always makes a fresh parse, so it sees the current statistics. It can therefore show the new plan while the application still runs the old one. The reverse can happen when someone changes the statistics, restores older ones, or changes the table definition between your test and the run you care about.
Adaptive features
Some plan decisions are made at run time, so no pre-execution parse can show them:
- Adaptive plans. The optimizer can include alternative subplans, such as a nested loops join and a hash join, and choose between them while the statement runs.
EXPLAIN PLANshows only the default plan.DISPLAY_CURSORshows the plan that was finally used, and the+ADAPTIVEmodifier shows the full set of alternatives. - Dynamic statistics. The optimizer may sample the tables at parse time when statistics are missing or insufficient. The result is stored with the cursor.
- Statistics feedback. After a first execution, Oracle can notice that its estimates were wrong and build a second child cursor with corrected estimates. The same SQL text then has several plans.
When a statement has several child cursors, always name the one you mean with cursor_child_no.
Plan controls
Oracle can change a plan without any change to your SQL text. A SQL plan baseline can force a stored plan. A SQL profile or SQL patch can attach extra hints or corrected estimates. These features apply when the statement is parsed for execution, and the real cursor's Note section tells you which ones were used. Always read the Note section of a DISPLAY_CURSOR plan before you assume that the optimizer chose the plan freely.
Summary of the causes
| Cause | Why EXPLAIN PLAN differs | How to check |
|---|---|---|
| Bind variable types | Binds are treated as `VARCHAR2` | Compare predicates for `TO_NUMBER` or `INTERNAL_FUNCTION` |
| Bind peeking | No values are peeked | Use `+PEEKED_BINDS` in `DISPLAY_CURSOR` |
| Session parameters | Your session differs from the application's | Compare `V$SES_OPTIMIZER_ENV` or `V$SQL_OPTIMIZER_ENV` |
| Statistics timing | Fresh parse versus an older cursor | Compare `LAST_LOAD_TIME` in `V$SQL` |
| Adaptive plans | Only the default plan is shown | Use `+ADAPTIVE` and read the Note section |
| Baselines, profiles, patches | These are applied when the real cursor is built | Read the Note section |
Comparing plan hash values
Every plan has a plan hash value, printed in the first line of DBMS_XPLAN output as Plan hash value:. It is a quick way to find out whether two plans are the same. Compare the value from your EXPLAIN PLAN with the one from the running cursor. If they match, the estimate was reliable for this statement. If they differ, trust the cursor.
You can list the cursors for a statement and their hash values from V$SQL:
SELECT sql_id, child_number, plan_hash_value, executions,
parsing_schema_name, last_load_time
FROM v$sql
WHERE sql_text LIKE 'SELECT /*+ GATHER_PLAN_STATISTICS */ last_name%'
AND sql_text NOT LIKE '%v$sql%';The next call then displays the plan of the specific child you found:
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(
sql_id => '&sql_id',
cursor_child_no => 0,
format => 'TYPICAL +PEEKED_BINDS'));Several rows with the same sql_id and different plan_hash_value values show that one statement has run with more than one plan. That is a common sign of bind-sensitive behavior or statistics feedback.
Other limits
EXPLAIN PLANgives no runtime information. It has noA-Rows,BuffersorA-Time, so you cannot see where the estimates went wrong.PLAN_TABLErows persist until you remove them.DISPLAYshows the most recent plan by default, but if several people share a plan table, pass astatement_idto avoid reading someone else's plan.- A statement cannot be explained if it references objects you cannot see. The plan for a view can also differ depending on who owns the objects.
When the estimate is enough
EXPLAIN PLAN is still useful in these cases:
- The statement is too expensive to run, such as a large
DELETEyou want to inspect first. - The statement has no bind variables, and your session settings match the application's.
- You want to check whether a new index could be used, before you build it in production.
For everything else, capture the real plan with DISPLAY_CURSOR, as the next chapter shows.
Exercise
A query filters a VARCHAR2 column with an application-supplied NUMBER bind. EXPLAIN PLAN shows an INDEX RANGE SCAN, but the application is slow. Give two reasons the plans can differ and say what you would run to see the real plan.
Show answer
EXPLAIN PLAN treats the bind as a VARCHAR2 and does not peek at its value. The real execution converts the column with TONUMBER, which prevents normal index use and leads to a full scan. Run the statement with a real bind (or find its sqlid in V$SQL), then call DBMSXPLAN.DISPLAYCURSOR with the sqlid, the cursorchildno and the format 'ALLSTATS LAST +PEEKEDBINDS'. Check the Predicate Information section for TO_NUMBER on the column.
Exercise
You gathered statistics on a table an hour ago. EXPLAIN PLAN shows a hash join, but V$SQL still shows the application's cursor with a nested loops plan. Name the likely cause and a column in V$SQL that supports it.
Show answer
The application cursor was built before the statistics change and has not yet been invalidated, because statistics gathering invalidates dependent cursors gradually. EXPLAIN PLAN does a fresh parse with the new statistics. LASTLOADTIME in V$SQL (and a different PLANHASHVALUE) supports this.