Sub topic 3
Getting the Actual Plan with DISPLAY_CURSOR
This chapter assumes you know SQL joins, WHERE and GROUP BY, and that you have run EXPLAIN PLAN before. You need access to the HR sample schema and the privileges to query V$SQL and V$SESSION.
Getting the Actual Plan with DISPLAY_CURSOR
EXPLAIN PLAN shows the optimizer's estimate, not the plan that ran. DBMSXPLAN.DISPLAYCURSOR reads the plan from the cursor cache, so it shows what the statement actually used. Add the GATHERPLANSTATISTICS hint to record row counts during execution.
SELECT /*+ GATHER_PLAN_STATISTICS */ 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_CURSOR(format => 'ALLSTATS LAST'));In SQL*Plus, run SET SERVEROUTPUT OFF first so the last statement in the session is your query and not a DBMS_OUTPUT call.
Actual Rows, Buffers and Time with ALLSTATS LAST
The ALLSTATS LAST format shows runtime statistics from the most recent execution:
- Starts: how many times the operation ran.
- E-Rows: rows the optimizer estimated.
- A-Rows: rows actually returned.
- Buffers: logical reads, meaning blocks accessed in memory.
- A-Time: actual elapsed time for the operation.
For an inner operation of a nested loop, Starts can exceed 1. A-Rows totals the rows across all starts.
Spotting Where Estimates and Actuals Diverge
Compare E-Rows with A-Rows for each operation. A gap of a factor of ten or more signals a cardinality misestimate. Start at the bottom of the tree. A wrong estimate there carries upward and can lead to a poor join method. High Buffers on an operation that returns few rows often points to a missing index or a poor access path.
> Note: A large gap is a symptom. Check whether optimizer statistics are stale before you add hints.
Looking at Past Plans with DISPLAY_AWR
Once a statement leaves the cursor cache, DISPLAYCURSOR returns nothing. DISPLAYAWR reads plans stored in the Automatic Workload Repository (AWR). It requires the sql_id, and it requires the Oracle Diagnostics Pack license.
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_AWR(
sql_id => '&sql_id',
format => 'TYPICAL'));Find the sql_id by searching V$SQL for your statement text.
A Step-by-Step Workflow for Reading a Plan
- Run the statement with the GATHERPLANSTATISTICS hint, then display it with DISPLAY_CURSOR.
- Read the tree from the bottom up, because the deepest operations run first.
- Compare E-Rows with A-Rows for each operation.
- Check Buffers on expensive operations and confirm the access and filter predicates.
- If the cursor is gone, use DISPLAY_AWR.
Exercise
A nested loop's inner operation shows Starts = 500 and A-Rows = 1200. Is the inner operation returning 1200 rows per start?
Show answer
No. A-Rows is the total across all 500 starts, so each start returned about 2.4 rows on average. Compare that average with the E-Rows value per start to judge the estimate.