| Lesson 4 | The EXPLAIN PLAN statement |
| Objective | Run EXPLAIN PLAN in Oracle 26ai, display its output, and interpret the plan tree while distinguishing estimates from execution evidence. |
Running EXPLAIN PLAN involves two separate statements: generate an estimated execution plan, then display the recorded operations. Oracle AI Database 26ai provides DBMS_XPLAN.DISPLAY for the second step. You do not need a locally written plan.sql script to format the result.
The distinction between explaining and executing is essential. EXPLAIN PLAN does not run the target SELECT or measure how long it takes. It records how the optimizer would process that statement in the explain environment. Use this estimate to understand access paths and joins, then obtain execution evidence when diagnosing an actual performance problem.
The preceding lesson covered Oracle PLAN_TABLE setup. In a normally configured 26ai database, Oracle supplies the global temporary table infrastructure and the PLAN_TABLE synonym. The definition is shared, while temporary plan rows are private to the session. Manual creation is an optional custom-table workflow, not a routine prerequisite.
Use a dedicated training connection and confirm access to the objects you intend to explain. The examples below use the optional HR and SH sample schemas. If those schemas are absent, use accessible training tables and adapt the column names. Being able to connect to a database does not automatically grant access to every sample table.
Keep generation and display in the same session. Two editor tabs can have separate database connections despite showing the same username. Also check whether a schema-local PLAN_TABLE overrides the public synonym. A stale local definition can cause problems that have nothing to do with the target query.
This HR example identifies employees in department 60. The account must have the privileges needed to explain the statement and insert its plan records into the output table.
EXPLAIN PLAN
SET STATEMENT_ID = 'L4_DEMO'
FOR
SELECT employee_id, last_name
FROM hr.employees
WHERE department_id = 60;
FOR introduces the SQL being explained. SET STATEMENT_ID assigns a label to its plan records. This is a label chosen by you, not the SQL_ID Oracle uses to identify a cached SQL statement. The command does not return the matching employees because it does not execute that SELECT.
Without an INTO clause, Oracle uses the default PLAN_TABLE name. If your workflow deliberately uses another output table, specify it with INTO and use the same name in the display call. The destination must already exist and have the required structure; EXPLAIN PLAN does not create it.
Use a fresh statement label for each comparison. If reusing a label, deliberately remove only your experiment's corresponding records in the training session before generating the replacement. An unrestricted deletion of all plan records is not a necessary first step.
EXPLAIN PLAN is DML and does not implicitly commit. Do not append a casual COMMIT to a tutorial command in a session that has pending application work. Transaction handling should follow the requirements of your output table and environment.
SELECT *
FROM TABLE(
DBMS_XPLAN.DISPLAY(
'PLAN_TABLE', 'L4_DEMO', 'TYPICAL'
)
);
The arguments specify the table, statement label and display format. This SELECT executes the display query, not the employee query being investigated. It formats the operation records generated in the preceding step.
In SQL*Plus, optional client settings can make a wide display easier to read:
SET LINESIZE 200
SET PAGESIZE 1000
These are SQL*Plus commands, not SQL statements to send through an application driver. They change presentation, not optimizer decisions. A graphical client may offer different controls for wrapping or exporting the displayed plan.
Start with TYPICAL for ordinary inspection. BASIC provides a compact operation-and-object view. ALL adds more information, such as projections and query-block details where available. The sections that appear depend on the statement and available information; a format option does not invent missing runtime measurements.
Begin with the statement and objects you expected to explain. Confirm that the output belongs to the intended experiment before judging any operation. Then inspect the tree, estimates and predicates together.
| Field | How to interpret it |
|---|---|
| Id and indentation | Identify an operation and its position in the parent-child tree. IDs are not elapsed-time markers. |
| Operation and Name | Identify the row-source operation and associated object, when one applies. |
| Rows and Bytes | Describe estimated cardinality and data volume, not measured output from this execution. |
| Cost (%CPU) | Shows an optimizer cost estimate and its estimated CPU component. Cost is not a duration in seconds. |
| Time | An estimated duration when shown, not a stopwatch measurement of the application request. |
| Pstart and Pstop | Describe partition access boundaries, which may be fixed values or runtime indicators. |
An asterisk beside an operation ID normally points to the corresponding Predicate Information entry. Access predicates and filter predicates help explain how conditions are used at that operation. Read them rather than inferring the complete filtering strategy from a short operation name.
Notes can provide additional context about optimizer decisions. Do not assume every query produces the same notes, or that a plan display proves every hint was effective. Review the information actually present and investigate unexpected choices using the relevant diagnostics.
A parent operation's cost can include work below it. Adding the displayed costs of every row together does not produce total execution time. Similarly, comparing two estimates is meaningful only when you understand whether the statements, data and optimizer environments are comparable.
The Sales History example calculates the average sale amount for each product category. It uses an explicit join condition and qualified column names so that the query's intent is visible independently of its physical plan.
EXPLAIN PLAN
SET STATEMENT_ID = 'L4_SALES_AVG'
FOR
SELECT p.prod_category,
AVG(s.amount_sold) AS average_amount_sold
FROM sh.sales s
JOIN sh.products p ON p.prod_id = s.prod_id
GROUP BY p.prod_category;
SELECT *
FROM TABLE(
DBMS_XPLAN.DISPLAY('PLAN_TABLE', 'L4_SALES_AVG', 'TYPICAL')
);
This example requires SH to be installed and accessible. The query does not contain a hint that selects a cost-based mode. Oracle's optimizer chooses the physical operations using its available information. Your installation may produce a different plan from the illustration below.
GROUP BY defines aggregation, not guaranteed presentation order. If the application requires sorted category names, specify ORDER BY as part of that requirement and inspect the resulting plan. Do not rely on a particular grouping implementation to return sorted rows.
Id Operation Object
0 SELECT STATEMENT
1 HASH GROUP BY
2 HASH JOIN
3 TABLE ACCESS FULL PRODUCTS
4 PARTITION RANGE ALL
5 TABLE ACCESS FULL SALES
The original numerical excerpt included estimates such as 489K rows and a cost of 1140. Those historical values are not current benchmarks. The structural representation retains the teaching example without presenting old costs and estimated times as fresh measurements.
The tabular display represents a tree. Indentation shows the relationships more clearly than the operation numbers alone. In this example, operation 0 is the root; operation 1 is its child; and operation 2 supplies rows to operation 1.
The arrows show rows flowing toward parent operations. Parent operators request rows from their children. A hash join has processing phases, and an aggregation can require input processing before returning groups. Consequently, the diagram is not a promise that every numbered operation runs once, to completion, in ascending or descending order.
Reading the leaves and following their parents is a useful way to understand this tree, but it is not a universal execution-timing rule. Repeated starts, parallel execution and adaptive behavior require additional context. Distinguish a plan's structural dependencies from a runtime timeline.
The diagram's partition range 1 through 16 belongs to the supplied example. It is not a statement that every SH database has exactly 16 SALES partitions. This query has no restrictive partition-key condition, so accessing the entire relevant range can be appropriate.
A whole-table aggregate can need a large fraction of its input rows. Reading those rows with full scans and joining them with a hash join can be reasonable. An index is not inherently faster when it leads to many additional table lookups.
Start with the result the application needs. Are the predicates correct? Does the query intentionally include the complete sales history? Are estimated row counts plausible? Then compare those expectations with measured work. A missing filter or unexpected row multiplication may matter more than replacing one access method.
Do not revive the legacy RULE hint as a tuning remedy. Investigate current optimizer inputs and actual execution behavior. A plan tells you what Oracle chose; it does not establish that an alternative is faster merely because that alternative uses an index.
An explained plan can differ from the one used during execution. Different schemas, statistics, bind information or optimizer settings can affect the choice. Explaining a statement after a slow request has finished does not recover that request's historical plan.
DBMS_XPLAN.DISPLAY_CURSOR reads a loaded cursor's plan rather than PLAN_TABLE. For a controlled test, collect row-source statistics during execution, for example:
SELECT /*+ GATHER_PLAN_STATISTICS */
e.employee_id, e.salary
FROM hr.employees e
WHERE e.department_id = 50;
Fetch all intended result rows when comparing complete executions. A client that stops after the first page can leave you examining partial work. The statistics-collection hint is for a deliberate measurement exercise, not an instruction to add diagnostics indiscriminately to production SQL.
Identify the SQL_ID and child cursor for that execution. In the following template, bind the two placeholders through your chosen client before running it:
SELECT *
FROM TABLE(
DBMS_XPLAN.DISPLAY_CURSOR(
:target_sql_id,
:target_child_number,
'ALLSTATS LAST'
)
);
Using NULL arguments for the last statement can be convenient when that context is known, but a client can execute intervening SQL. Explicit identification avoids accidentally inspecting a different cursor. The account needs the performance-view access documented for DISPLAY_CURSOR; ask the DBA for suitable permissions rather than requesting unrestricted administrative access.
ALLSTATS LAST does not retroactively collect missing statistics. Compare E-Rows and A-Rows together with Starts and other measurements: an operation that starts repeatedly needs different interpretation from one that starts once. If the relevant cursor is no longer cached, a new EXPLAIN PLAN is a new estimate, not a replacement for lost execution evidence.
Identify the two children of HASH JOIN in the illustrated tree. Explain why the SALES scan has a partition operation above it, and why this broad aggregate does not automatically benefit from replacing full scans with index lookups.
Finally, distinguish the two measurements you might want: the optimizer's estimated rows and the rows produced during a controlled execution. EXPLAIN PLAN provides the first kind of information; collected cursor statistics support the second. The next lesson examines full-table scans in more detail.