Sub topic 2
Generating a plan with EXPLAIN PLAN and DBMS_XPLAN.DISPLAY
This chapter assumes you can write SELECT statements with joins and WHERE clauses. It also assumes you can connect to an Oracle schema such as HR with SQL*Plus, SQL Developer or SQLcl. You do not need to know how to read a plan yet. The next chapter covers that. Here you learn how to produce one.
What EXPLAIN PLAN does
EXPLAIN PLAN asks the optimizer how it would run a statement. It does not run the statement. The optimizer parses the SQL, picks a plan using the current statistics and session settings, and writes the plan as rows into a table. Nothing is fetched, and no data is changed, even for an UPDATE or DELETE.
The statement does not print anything itself. It stores the plan, and you then format the stored rows with the DBMS_XPLAN package. Producing a plan therefore takes two steps:
- Run
EXPLAIN PLAN FOR <statement>. - Run
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY)to format the stored rows.
A first plan
Run this in the HR schema:
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
WHERE e.salary > 10000;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);SQL*Plus answers the first statement with Explained. The second statement returns text like the following. The numbers are illustrative, and your hash value, row counts and costs will differ:
Plan hash value: 2052257371
--------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 15 | 300 | 5 (0)| 00:00:01 |
| 1 | NESTED LOOPS | | 15 | 300 | 5 (0)| 00:00:01 |
|* 2 | TABLE ACCESS FULL | EMPLOYEES | 15 | 180 | 3 (0)| 00:00:01 |
| 3 | TABLE ACCESS BY INDEX ROWID| DEPARTMENTS | 1 | 8 | 1 (0)| 00:00:01 |
|* 4 | INDEX UNIQUE SCAN | DEPT_ID_PK | 1 | | 0 (0)| 00:00:01 |
--------------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter("E"."SALARY">10000)
4 - access("D"."DEPARTMENT_ID"="E"."DEPARTMENT_ID")Three things are worth noting before you learn to interpret it:
- The plan hash value is a number computed from the plan's shape. Two plans with the same hash value have the same operations in the same order.
- The Rows, Bytes, Cost and Time columns are the optimizer's estimates. No row was read to produce them.
- The
*beside an Id means that line has an entry in the Predicate Information section.
Where the plan is stored: PLAN_TABLE
EXPLAIN PLAN inserts its output into a table named PLAN_TABLE. Since Oracle Database 10g, every database includes a shared global temporary table called SYS.PLAN_TABLE$, with a public synonym PLAN_TABLE. This table has two properties that matter:
- Rows are private to your session. Other sessions cannot see your plans.
- Rows disappear when the session ends, so you do not have to clean up.
Older databases, or a table you created yourself, may lack this setup. In that case, create your own copy by running the utlxplan.sql script, which ships under $ORACLE_HOME/rdbms/admin. In SQL*Plus:
@?/rdbms/admin/utlxplan.sqlThe table's columns hold one row per plan operation, including its Id, parent Id, operation name, object name, and the cost and cardinality estimates. DBMS_XPLAN.DISPLAY joins those rows back into the tree you see in the output.
Naming a plan with STATEMENT_ID and INTO
With no options, DBMS_XPLAN.DISPLAY shows the most recent plan inserted into PLAN_TABLE. That is convenient, but it breaks down if you explain several statements and want to compare them. Use SET STATEMENT_ID to tag each plan with a label:
EXPLAIN PLAN
SET STATEMENT_ID = 'dept50'
FOR
SELECT last_name
FROM hr.employees
WHERE department_id = 50;
EXPLAIN PLAN
SET STATEMENT_ID = 'sal10k'
FOR
SELECT last_name
FROM hr.employees
WHERE salary > 10000;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY(
table_name => 'PLAN_TABLE',
statement_id => 'dept50'));The parameters of DBMS_XPLAN.DISPLAY are:
| Parameter | Default | Meaning |
|---|---|---|
| `table_name` | `PLAN_TABLE` | The table that holds the plan rows. |
| `statement_id` | `NULL` | The label set with `SET STATEMENT_ID`. `NULL` means the latest plan in the table. |
| `format` | `TYPICAL` | Which columns and sections to print. The next chapters cover this. |
| `filter_preds` | `NULL` | A SQL condition that selects among plans, for example `plan_id = 42`. |
If you want the rows in a table other than the default, add INTO:
EXPLAIN PLAN
SET STATEMENT_ID = 'dept50'
INTO my_plan_table
FOR
SELECT last_name FROM hr.employees WHERE department_id = 50;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY('MY_PLAN_TABLE', 'dept50'));The table named in INTO must have the standard PLAN_TABLE columns. A permanent table is useful when you want to keep plans across sessions, for example to compare a plan before and after a change.
What you can explain
EXPLAIN PLAN accepts SELECT, INSERT, UPDATE, DELETE and MERGE. It also accepts CREATE TABLE ... AS SELECT and CREATE INDEX. Because it only plans the statement, it is safe to use on a destructive statement:
EXPLAIN PLAN FOR
DELETE FROM hr.employees WHERE department_id = 50;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
ROLLBACK;No employee row is deleted. The ROLLBACK here is a habit rather than a need, because EXPLAIN PLAN itself changes only your private PLAN_TABLE. Note that this does not mean the statement is harmless in every respect. You need the privileges to run the statement, and the optimizer does take locks on the objects it parses.
Formatting the output
DBMS_XPLAN.DISPLAY is a table function, so you call it through TABLE(...) and select from it like any other row source. It returns one row per line of text. Two practical points follow:
- Output lines can be long. In SQL*Plus, run
SET LINESIZE 200andSET PAGESIZE 100first, or the plan may wrap and become unreadable. - Because it is a query, you can wrap it in a script, a spooled file or a view without special handling.
The format argument selects how much detail to show. Here is a minimal layout with the predicate section added:
EXPLAIN PLAN FOR
SELECT last_name FROM hr.employees WHERE department_id = 50;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY(format => 'BASIC +PREDICATE'));BASIC prints only the Id, Operation and Name columns. The +PREDICATE modifier adds the Predicate Information section back. A later chapter covers the full list of formats.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ORA-00942: table or view does not exist` on `EXPLAIN PLAN` | No `PLAN_TABLE` is visible, or you lack access to a table in the statement. | Run `utlxplan.sql`, or check your privileges on the objects in the query. |
| `ORA-01031: insufficient privileges` | You can't run the underlying statement. | Get the privileges the statement needs. `EXPLAIN PLAN` does not bypass them. |
| `Error: cannot fetch plan for statement_id 'xyz'` | The statement id is misspelled, is in a different table, or the session ended. | Check the spelling and case, and the `table_name`. Statement ids are case sensitive. |
| An old plan appears | `DISPLAY` shows the latest plan in the table, and your `EXPLAIN PLAN` failed or was not run. | Re-run `EXPLAIN PLAN` and confirm it printed `Explained.` |
| Wrapped, garbled output | The line size is too small. | Increase `LINESIZE`. |
Exercise
You run EXPLAIN PLAN SET STATEMENT_ID = 'q1' FOR SELECT * FROM hr.jobs; and then EXPLAIN PLAN SET STATEMENT_ID = 'q2' FOR SELECT * FROM hr.regions;. Write the query that shows the plan for the first statement, and say what SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY) would show instead.
Show answer
Use SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY(table_name => 'PLAN_TABLE', statement_id => 'q1'));. With no arguments, DISPLAY shows the most recently inserted plan in PLAN_TABLE, which is the plan for q2 (the hr.regions query).
Exercise
Does EXPLAIN PLAN FOR UPDATE hr.employees SET salary = salary * 2 change any salary? Which rows does it write, and where?
Show answer
No salary changes, because the statement is parsed and planned but not run. It writes plan rows into PLAN_TABLE, which is a session-private table, so the rows are visible only to your session and vanish when it ends.