| Lesson 8 | Tuning SQL with Hints |
| Objective | Explain how optimizer hints influence access paths and how to verify their use and measure their effects. |
An Oracle SQL hint lets you test a decision that the optimizer would otherwise make. For example, you can ask Oracle AI Database 26ai to read a table with a full scan or use a named index. This is useful when investigating a slow statement: changing one access decision can help reveal where the work is being spent. It does not establish that your preferred plan is better. That conclusion requires evidence from execution.
This lesson connects the execution-plan tools, optimizer goals, and cardinality estimates introduced earlier in the module. You will compare three versions of a query, inspect the relevant cursor, check whether its hint was used, and decide what the observations justify. The SQL below is instructional and has not been executed to produce benchmark results for this article.
An access path is the way Oracle retrieves rows from a table or data from an index. A table scan reads table blocks and applies the relevant predicates. An index access can locate candidate entries and then visit table rows for additional columns. Depending on the query and available indexes, some operations can obtain everything they need from indexes alone.
Consider a request for employees in one department. The optimizer estimates how many employees qualify and the work involved in alternative plans. An index may narrow the search effectively. If many rows qualify, the repeated table visits associated with index access can make a scan competitive. Table size, data distribution, clustering, available columns, and the broader query all matter. There is no universal percentage of rows at which one access path becomes the winner.
A hint can constrain this choice for a particular table reference. It does not change which employees the predicate requests. Keep three other decisions separate: a join method describes how row sets are combined, a join order describes their sequence, and an optimizer goal influences the objective of optimization. Choosing an index for one table does not prescribe every other operation in a multitable plan.
The earlier cost-based optimizer lesson explains why estimated row counts matter. Estimates can differ from observed cardinalities, but it is incorrect to say that Oracle cannot estimate rows at all. A hint experiment tests an alternative; it does not remove the need to investigate the reason for a poor estimate.
Place the hint comment immediately after SELECT. The plus sign belongs directly after the opening asterisk. Refer to a table by its alias when the SQL supplies one, and do not include the schema name in the hint's table reference. These rules are documented in the Oracle 26ai SQL Language Reference.
SELECT /*+ FULL(e) */
e.employee_id, e.last_name
FROM hr.employees e
WHERE e.department_id = 50;
Here, e identifies the same table reference in the hint, selected columns, and predicate. The ordinary comment /* FULL(e) */ is not a hint. A comment placed elsewhere in the statement should not be assumed to control optimization. SQL can remain valid even when a hint is not recognized, so successful execution alone is an inadequate check.
Hints also have query-block scope. A query containing subqueries or views can have several blocks, and transformations can affect how references are resolved. Begin with a simple statement while learning the syntax. For a complex statement, use the plan's query-block and alias information to establish the intended target before adding more instructions. Do not copy a hint from another statement merely because both contain an alias called e.
| Hint | Requested behavior | What to check |
|---|---|---|
FULL(e) | Use a full scan of the referenced table. | The table operation and rows processed. |
INDEX(e EMP_DEPARTMENT_IX) | Use the specified available index. | The index operation and any subsequent table access. |
NO_INDEX(e EMP_DEPARTMENT_IX) | Exclude that index from consideration. | Which remaining access path is selected. |
NO_INDEX is not equivalent to FULL: excluding one index can leave other indexes available. Likewise, the generic INDEX hint does not mean that every query will display an index range scan. Read the operation actually selected. A hint can be inapplicable, unresolved, or in conflict with another instruction; the hint report helps distinguish these cases from a genuine change in access.
For an initial experiment, avoid mixing access-path, join, parallelism, and optimizer-goal changes. If several changes are introduced together, a faster result does not identify which one helped. Keep the test small enough that you can explain the difference between its baseline and candidate.
The following examples require access to HR.EMPLOYEES and its department index. HR is an optional sample schema, not a guaranteed part of every installation. Use a training database with appropriate permissions. If your sample schema has been modified, verify the object definitions and adapt the names before continuing.
SELECT index_name, column_name, column_position
FROM all_ind_columns
WHERE table_owner = 'HR'
AND table_name = 'EMPLOYEES'
ORDER BY index_name, column_position;
The example uses EMP_DEPARTMENT_IX. Confirm that an appropriate usable index exists rather than assuming that a plausible name identifies an object. This column listing is an inventory aid, not a complete index-health check. If an expected index is absent, stop and resolve the prerequisite; adding its name to a hint will not create it.
Choose a consistent measurement objective. These examples compare retrieval of the complete result. Fetch every row for each version, using the same client behavior. An application interested in the first screen of results needs an explicitly different test, as discussed in SQL optimizer modes. Do not compare one version's first page with another version's full result.
SELECT /*+ GATHER_PLAN_STATISTICS */
e.employee_id, e.last_name, e.department_id
FROM hr.employees e
WHERE e.department_id = 50;
The baseline includes instrumentation but no access-path instruction. GATHER_PLAN_STATISTICS enables the runtime information used in the comparison. Use it consistently for all three variants. After this query finishes, inspect its cursor using the diagnostic call in the next section before running another variant.
SELECT /*+ GATHER_PLAN_STATISTICS FULL(e) */
e.employee_id, e.last_name, e.department_id
FROM hr.employees e
WHERE e.department_id = 50;
The predicate and selected columns are unchanged. If the baseline already used a full scan, this version may not introduce the difference you expected. That is a useful observation: adding a hint is not itself proof that the plan changed. Record the actual operation and inspect this version's cursor separately.
SELECT /*+ GATHER_PLAN_STATISTICS INDEX(e EMP_DEPARTMENT_IX) */
e.employee_id, e.last_name, e.department_id
FROM hr.employees e
WHERE e.department_id = 50;
The department index can help identify matching rows, but the query also requests employee identifiers and last names. Do not assume that all requested data resides in that index. Examine any table lookup after the index operation, because those visits contribute to the work. Retain the same projection when comparing variants; removing columns could create a different experiment.
A small HR table is convenient for learning this procedure. Its timings may be too short or too sensitive to client overhead to support a meaningful performance conclusion. Demonstrating the syntax is useful even when the experiment finds no improvement. Production decisions require representative data and workload conditions.
Immediately after each test query, in the same session, run:
SELECT *
FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(
NULL, NULL, 'ALLSTATS LAST +HINT_REPORT'));
DISPLAY_CURSOR displays a cached cursor, while ALLSTATS LAST requests collected statistics for its last execution. It does not retrospectively collect statistics that were never captured. The DBMS_XPLAN reference documents the formats and the required access to V$SQL, V$SQL_PLAN, V$SESSION, and V$SQL_PLAN_STATISTICS_ALL.
With null identifiers, this convenience call relies on the previous statement in the session. Client-generated SQL can interfere with that assumption. Check the displayed SQL text. If it is not your test statement, identify the intended SQL ID and child cursor and pass those values explicitly. A permissions error or missing cursor is a diagnostic prerequisite problem, not proof that the access hint was rejected.
For a more complete hint listing, inspect that same identified cursor with the format ALL +HINT_REPORT. The report identifies unused hints and relevant resolution or syntax problems; read the legend printed with your output. Oracle's hint usage documentation explains that hints can be ignored without SQL errors and distinguishes reporting formats.
Check both the report and the operation tree. A recognizable hint comment does not establish that its target exists, and a desired operation could already have been selected without the hint. The SQL Analysis Report is a separate diagnostic feature; it should not be described as another name for the hint usage report.
By comparison, EXPLAIN PLAN describes a proposed plan without running the query. It is useful for exploration, but it cannot prove reduced elapsed time. The distinction from the earlier EXPLAIN PLAN lesson is central here: a tuning decision needs execution evidence as well as a plausible plan.
Create a small results sheet for the baseline, full-scan candidate, and index candidate. Save the SQL text, SQL ID and child number, plan output, input values, and measurement conditions together. These details make it possible to repeat the experiment and prevent a later screenshot from being mistaken for evidence about a different statement.
A lower optimizer cost is an estimate, not a stopwatch result. A plan with fewer displayed lines is not necessarily cheaper to execute. Likewise, an index operation is not inherently more efficient than a table scan. Explain the observed work instead of judging a plan by whether it contains an operation that sounds desirable.
Cache state, concurrent activity, parsing, and client output can affect timings. SQL*Plus SET TIMING ON provides useful elapsed-time context, but it does not isolate all server work. Do not flush shared production caches to make a classroom comparison look clean. Record the conditions and repeat carefully in an appropriate environment.
Finally, test more than one representative input. Department 50 is a teaching value, not evidence that every department behaves similarly. A plan that benefits a rare value might hurt a common value. If the application uses binds, evaluate that application behavior rather than assuming a literal-based demonstration captures every relevant execution case.
Suppose all three versions display the same access operation. First check that each saved plan belongs to the intended SQL text. Then inspect whether the candidate instruction was used and whether its alias resolves to the expected table. An unchanged plan can mean the baseline already made that choice; it can also indicate that the requested alternative was not applicable. Those explanations lead to different next steps.
Suppose the index candidate changes the plan but takes longer. Look beyond the index line. The table visits needed to retrieve additional columns may dominate the execution. Verify the amount of work and qualifying rows before concluding that an index is defective. The experiment may simply demonstrate that this request is better served by a scan under the tested conditions.
Suppose a candidate appears faster only on its second execution. Repeat the baseline too, and vary the order of your comparisons. Otherwise, a difference associated with warmed data or changing workload may be attributed to the hint. Keep the measurements together instead of reporting a single favorable timing. Small differences on a tiny sample table deserve particularly cautious interpretation.
Suppose the report lacks actual row statistics. Confirm that instrumentation was present in the executed statement, that the displayed cursor is correct, and that the execution fetched the intended result. Do not replace missing observations with the estimated Rows column. A clearly recorded incomplete test is more useful than a confident conclusion based on a mixture of estimates and unrelated executions.
These checks make the experiment reproducible. A colleague should be able to identify the original problem, repeat the same request, find the same diagnostic evidence, and understand what would invalidate the conclusion. That record is the basis for deciding whether a hint belongs in maintained application SQL or remains only a temporary investigative tool.
INDEX_JOIN concerns combining indexes belonging to one table so that the required data can be obtained without table access. It does not instruct Oracle how to join an employees table to a departments table. INDEX_FFS requests a fast full index scan, which does not promise index-key ordering. Both require an applicable access path, and index-only plans require sufficient index coverage.
For example, changing a narrow projection into SELECT * can invalidate the reasoning behind an index-only experiment. Conversely, dropping a required column just to obtain such a plan changes the application request. Begin with what the application must return, then examine the available access methods. Consult the SQL Language Reference before introducing specialized hints, rather than treating a list of hint names as a tuning recipe.
If a candidate improves representative executions, investigate why. An estimate problem, an unsuitable predicate, missing indexing, or changed data may call for a more durable correction. If neither candidate improves the workload, retain the baseline and use the evidence to choose the next question. A failed hypothesis still narrows the investigation.
Document any retained hint with its purpose, measured benefit, affected inputs, and review conditions. Recheck it after significant data growth, schema changes, or database upgrades. A restriction that helped today can prevent a better access choice later. Plan-management and advisor facilities may also be relevant, subject to the deployment's edition, services, and licensing; they are not prerequisites for this introductory experiment.
The historical RULE hint is not the modern alternative demonstrated here. This lesson tests access decisions within cost-based optimization. The practical sequence is to establish a baseline, change one decision, verify that Oracle used the instruction, and compare actual work against the application's objective. Continue to the module conclusion to bring these tuning techniques together.