| Lesson 3 | Basic SQL tuning tools |
| Objective | Explain the tool set for SQL tuning. |
SQL tuning starts with a question about evidence: which statement is responsible for the work, which plan does it use, and where does its execution spend time? Oracle AI Database 26ai provides several ways to investigate these questions. Choosing the right tool matters because an estimated plan, an executed cursor's plan, and measured execution statistics answer different questions.
In the previous lesson on Oracle SQL extensions, a function-based index gave the optimizer another access option. It did not guarantee faster execution. The tools in this lesson help you examine that kind of change before deciding whether to keep it. Start with correct results and a representative workload, then gather evidence appropriate to the performance problem.
| Question | Starting tool | Limit to remember |
|---|---|---|
| What plan would Oracle choose in this environment? | EXPLAIN PLAN and DBMS_XPLAN.DISPLAY | The target statement is not executed, so there are no measured runtime results. |
| Which plan belongs to a cursor that executed? | DBMS_XPLAN.DISPLAY_CURSOR | Identify the correct cursor; detailed runtime statistics must have been collected. |
| How long does a client run take? | SQL*Plus SET TIMING ON | Client-observed elapsed time is not a server-only CPU measurement. |
| What happened during parse, execute, and fetch? | SQL Trace and TKPROF | Trace collection adds overhead and requires controlled access to trace files. |
| What happened across a workload or during a monitored execution? | AWR, ADDM, advisors, or SQL Monitoring | Check feature availability and entitlement for the database offering. |
These are different kinds of tools. SQL*Plus is a client application, EXPLAIN PLAN is a SQL statement, DBMS_XPLAN is a PL/SQL package, and TKPROF is an operating-system utility. A graphical worksheet may make them easier to use, but an Explain Plan button does not turn an estimate into a measurement.
EXPLAIN PLAN records the optimizer's proposed operations in a plan table. DBMS_XPLAN.DISPLAY formats that information. This is useful when reviewing a statement before running it or exploring how the optimizer interprets its predicates. It does not execute the target SELECT or establish how long the query will take.
The following examples assume the optional HR sample schema is installed and that your account can query HR.EMPLOYEES. Use an approved practice environment. If HR is unavailable, adapt the query to a table you are allowed to inspect.
EXPLAIN PLAN SET STATEMENT_ID = 'M2L3_ESTIMATE' FOR
SELECT employee_id, last_name
FROM hr.employees
WHERE department_id = 50;
SELECT *
FROM TABLE(DBMS_XPLAN.DISPLAY(NULL, 'M2L3_ESTIMATE', 'TYPICAL'));
The statement identifier associates the display request with this explained statement. Read the operations, object names, estimated rows, and predicate information together. An index operation may be suitable for a selective search, while a table scan may be reasonable when much of the table is needed. Neither operation is automatically evidence of a good or bad query.
Optimizer cost is a comparative estimate of work, not elapsed seconds. An explained plan can differ from the plan used by an executed statement because the environment, bind values or datatypes, and other optimization inputs may differ. Use an executed cursor's plan when investigating what a particular application statement actually used.
Modern Oracle databases normally supply PLAN_TABLE through a system-created temporary table and synonym. Running utlxplan.sql is not a universal first step. If the plan table is unavailable, investigate configuration and privileges with the DBA. Your account needs access to the statement's objects and the privileges needed to populate and read the plan output.
DBMS_XPLAN.DISPLAY_CURSOR displays a plan from the cursor cache. When row-source statistics were collected, it can also show measured work for plan operations. A SQL_ID identifies SQL text, and a child cursor number distinguishes a particular child under that SQL_ID. Different children can have different execution characteristics, so record both when investigating a production statement.
SELECT /*+ gather_plan_statistics */ employee_id, last_name
FROM hr.employees
WHERE department_id = 50;
SELECT *
FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST'));
Fetch the first query to completion, then run the display query immediately in the same session. The NULL defaults make this a convenient short demonstration, but client-generated SQL can change which cursor is considered the last statement. For a repeatable investigation, supply the SQL_ID and child number captured for the target statement instead of relying on those defaults.
The gather_plan_statistics hint requests statistics for this statement. ALLSTATS LAST asks the display function to show available statistics for the last execution; it does not collect missing statistics retroactively. An aged-out cursor or an execution without the required collection may not provide the evidence you need. Do not change database-wide statistics settings merely to follow this example.
E-Rows represents estimated rows, A-Rows reports actual rows when available, and Starts indicates how often an operation began. An operation inside a nested loop can start many times. Consider A-Rows together with Starts before comparing it with a per-start estimate. Buffers helps describe logical buffer work; it is not a direct count of physical storage reads.
A large estimation difference is a reason to investigate data distribution, predicates, bind values, and statistics. It is not proof that an index must be added. Compare the statement's complete work and elapsed time, including whether all rows were fetched. Returning the first screen of rows is a different test from processing the entire result.
V$SQL supplies cursor-level information and statistics; V$SQL_PLAN describes plan operations; V$SQL_PLAN_STATISTICS_ALL combines plan information with available execution statistics. V$SQL_WORKAREA describes work areas used by SQL operations. Cursor-level totals may span multiple executions, so do not label them as one request's measurements.
DISPLAY_CURSOR requires appropriate SELECT or READ access to its underlying fixed views, including V$SQL, V$SQL_PLAN, V$SESSION, and V$SQL_PLAN_STATISTICS_ALL. Ask the DBA for the necessary access. SYSDBA is not the normal account to use for this learning workflow.
SET TIMING ON
SELECT employee_id, last_name
FROM hr.employees
WHERE department_id = 50;
SET TIMING OFF
SET TIMING is a SQL*Plus client command. It helps compare elapsed time for commands run through that client, but it does not isolate server CPU time or explain the reason for a delay. Client behavior, network transfer, and fetching affect the context of the result.
Keep the data, parameter values, fetch completion, client settings, and workload conditions comparable. Repeat a representative test rather than treating one fast run as conclusive. Cache state and concurrent activity can influence results. Record what you measured so another person can reproduce the comparison.
SQL*Plus AUTOTRACE can report a plan and statement statistics after execution. It requires the appropriate setup and privileges. Its plan output should not be assumed to be the executed cursor's plan, and its statement statistics are not a substitute for per-operation runtime evidence. Use it when that level of reporting answers the question.
When a plan does not explain the observed behavior, tracing can show activity across parse, execute, and fetch calls. These stages matter: a statement can spend resources preparing to execute, doing database work, or fetching rows back to its caller. A trace also helps distinguish repeated small calls from a single expensive execution.
The following PL/SQL enables tracing for the current session with wait information and without bind-value capture. Run only the short workload being investigated between the two blocks.
BEGIN
DBMS_SESSION.SESSION_TRACE_ENABLE(waits => TRUE, binds => FALSE);
END;
/
-- Run the statement or short workload being investigated here.
BEGIN
DBMS_SESSION.SESSION_TRACE_DISABLE;
END;
/
The slash is a SQL*Plus script delimiter. Ensure session tracing is disabled even if the test fails. Keep the scope and duration small because tracing consumes resources and storage. A DBA can use DBMS_MONITOR for appropriate session, service, or application tracing when the investigation extends beyond the current session. Coordinate trace-file access rather than assuming a client can read server files directly.
TKPROF formats an existing trace file into a readable report. Run it from an operating-system shell where the utility and trace file are available. The filenames below are placeholders:
tkprof input.trc output.prf
Review call counts, rows processed, and resource consumption together. Frequent executions can make a modest statement significant to the workload. TKPROF does not turn tracing on. Its optional EXPLAIN facility generates an explained plan later, which is not proof of the plan used during the traced execution.
A single-statement investigation is sometimes too narrow. Automatic Workload Repository (AWR) retains workload information, while Automatic Database Diagnostic Monitor (ADDM) analyzes performance findings. SQL Tuning Advisor examines statements and suggests tuning actions. SQL Access Advisor evaluates access structures for a workload. Recommendations require review and testing against application requirements.
Real-Time SQL Monitoring provides details about monitored executions. SQL Performance Analyzer (SPA) evaluates the effect of changes on a SQL workload. SPA is a different tool from the historical SQL Analyze interface. The old rule-based-plan simulation and Index Tuning Wizard click sequence do not describe the current workflow.
| Feature family | Examples | Licensing category |
|---|---|---|
| Workload diagnostics | AWR, ADDM, Active Session History | Oracle Diagnostics Pack |
| Tuning and monitored execution | SQL Tuning Advisor, SQL Access Advisor, Real-Time SQL Monitoring | Oracle Tuning Pack, with Diagnostics Pack as a prerequisite |
| SQL workload change testing | SQL Performance Analyzer | Oracle Real Application Testing |
Availability and whether a feature is included or separately licensed depend on the database offering, including Free and cloud offerings. Consult the Oracle 26ai Licensing Information for your deployment. CONTROL_MANAGEMENT_PACK_ACCESS controls functionality, not entitlement. Access through a graphical tool or command-line API does not remove the feature's licensing requirements.
These examples illustrate tool use; they do not provide measured results for your database. The next lesson explains how Oracle executes SQL, giving more context for the parse, execution, and fetch activity exposed by these tools.