Sub topic 14
How the optimizer treats subqueries
This chapter assumes you can write correlated subqueries, IN/NOT IN, and EXISTS/NOT EXISTS, and that you have run EXPLAIN PLAN at least once. You also need the HR sample schema. The earlier chapters described how a correlated subquery behaves logically: the inner query runs once per outer row. Oracle does not always execute it that way. The optimizer is free to rewrite the statement as long as it returns the same rows. This chapter explains what it does, how to see it, and when to override it.
Logical meaning versus physical execution
SQL describes a result, not a procedure. "Evaluate once per outer row" is the definition of the result. The optimizer is allowed to pick any strategy that produces the same rows.
For subqueries, Oracle has three main strategies:
- Unnesting. The subquery is turned into a join, usually a semi-join or an anti-join, and the whole statement is optimized as a single query block.
- Filter execution. The subquery stays as a separate block that runs repeatedly as a
FILTER, with some result caching. - View merging or materialization. Inline views and
WITHqueries are either folded into the outer query or computed once and stored.
Semi-joins and anti-joins
A semi-join returns each row of the outer table at most once, if at least one matching row exists on the other side. It never multiplies rows, even if several matches exist. That is exactly what IN and EXISTS mean. An anti-join returns outer rows that have no match, which is what NOT EXISTS and NOT IN mean.
You cannot write a semi-join directly in Oracle SQL. It exists only as a plan operation. Consider this query:
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id);An ordinary join of departments to employees would repeat a department once for every employee in it. A semi-join stops searching a department after the first matching employee. That is why rewriting EXISTS as a plain join needs a DISTINCT, while the optimizer's semi-join needs nothing extra.
Reading the plan
Use EXPLAIN PLAN and DBMS_XPLAN.DISPLAY to see what the optimizer chose:
EXPLAIN PLAN FOR
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id);
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);The operation names tell you which strategy was used. Exact plans depend on version, statistics, and indexes, so treat the following as a guide to the names rather than a promise of output.
| Plan operation | Meaning |
|---|---|
| `HASH JOIN SEMI` or `NESTED LOOPS SEMI` | An `IN` or `EXISTS` subquery was unnested into a semi-join. |
| `HASH JOIN ANTI` or `NESTED LOOPS ANTI` | A `NOT EXISTS` or `NOT IN` subquery was unnested into an anti-join. |
| `HASH JOIN ANTI NA` | A null-aware anti-join, used for `NOT IN` when NULLs are possible. |
| `FILTER` | The subquery was not unnested. It runs as a child step, repeatedly. |
| `VIEW` | An inline view or `WITH` query kept as its own block. |
| `TEMP TABLE TRANSFORMATION` | A `WITH` query was materialized into a temporary table. |
If you see a FILTER with two children, the second child is the subquery. The number of executions appears in the Starts column when you collect row-source statistics.
Why unnesting is not always allowed
Unnesting must not change the result. Oracle only does it when it can prove equivalence. A few cases block it or force extra care:
- A subquery containing
ROWNUM, or other constructs whose result depends on the order of evaluation. - A subquery that appears inside an
ORwith other conditions, since a single semi-join cannot express a disjunction. - A scalar subquery in the
SELECTlist. This has to return one value for each outer row, so it is normally run per row rather than joined. Some releases can transform certain scalar subqueries into outer joins, but you should not rely on that.
NOT IN and the null-aware anti-join
Earlier you saw that NOT IN returns no rows when the subquery returns a NULL. The optimizer must preserve that behavior. If both columns are declared NOT NULL, or the subquery has a WHERE ... IS NOT NULL filter, Oracle can use an ordinary anti-join. If either side may contain NULLs, it needs a special operator. Since Oracle Database 11g, that operator is the null-aware anti-join (ANTI NA).
EXPLAIN PLAN FOR
SELECT last_name
FROM employees
WHERE employee_id NOT IN (SELECT manager_id FROM employees);
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);The plan may be efficient, but the result is still empty, because manager_id has a NULL. The optimizer makes the query fast without making it do what you probably meant. This is why NOT EXISTS is usually the better first choice: its meaning matches the intent, and it unnests to an ordinary anti-join.
Filter execution and subquery caching
When Oracle keeps a correlated subquery as a FILTER, it does not always run it once per outer row. It keeps a small in-memory cache that maps the values passed from the outer query to the subquery result. If many outer rows share the same correlation value, the subquery runs once per distinct value and later rows reuse the cached answer.
Consider the correlated average query from earlier:
SELECT e.employee_id, e.last_name, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(i.salary)
FROM employees i
WHERE i.department_id = e.department_id);With 107 employees and 11 distinct department values, a filter plan with caching executes the subquery about 11 times, not 107. Caching is much less useful when the correlation column has many distinct values, such as a primary key. The cache has a fixed size and may discard entries on hash collisions, so the benefit is not guaranteed.
The same idea applies to scalar subqueries in the SELECT list. One commonly used trick is to wrap a function call in a scalar subquery, as in (SELECT my_func(e.department_id) FROM dual). This lets the cache avoid repeated calls with the same input.
Controlling the decision with hints
Normally you should let the optimizer choose. When you have evidence from a plan and its runtime statistics that the choice is poor, hints can override it. The UNNEST and NO_UNNEST hints go inside the subquery block:
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT /*+ NO_UNNEST */ 1
FROM employees e
WHERE e.department_id = d.department_id);NO_UNNEST forces a FILTER. This may be better when the outer query returns very few rows and the subquery is cheap with an index. UNNEST asks for the join form.
For WITH queries, the MATERIALIZE and INLINE hints control whether the result is stored in a temporary table or merged into the main query. These two hints are widely used but are not described in the official documentation, so treat them as less stable than the others. Without a hint, Oracle normally materializes a WITH query only when it is referenced more than once and the cost estimate favors it.
The MERGE and NO_MERGE hints do the same for inline views. A merged view lets the optimizer push predicates and join orders across the boundary. Views containing GROUP BY, DISTINCT, or analytic functions often cannot be merged simply.
Practical consequences
- Write the form that states your intent.
INandEXISTSusually perform the same after unnesting, so choose by readability and NULL behavior. - Do not assume a correlated subquery is slow because it "runs per row". Look at the plan first.
- Do not assume a join is faster than a subquery. Semi-joins can beat joins with
DISTINCTbecause they stop at the first match. - When timing a query, compare plans and actual row counts, not only elapsed time, since caching and buffer contents change results between runs.
Exercise
A query uses WHERE employeeid NOT IN (SELECT managerid FROM employees) and the plan shows HASH JOIN ANTI NA. The query returns no rows. Explain why the plan is efficient but the result is empty, and give a rewrite that returns employees who manage nobody.
Show answer
The ANTI NA operator is the null-aware anti-join that Oracle uses when the subquery column can contain NULLs. It implements NOT IN semantics exactly: because managerid contains a NULL (the top-level employee), the NOT IN condition is never true, so no rows qualify. The plan is efficient, but the SQL itself does not express what was intended. Rewrite it with NOT EXISTS: SELECT e.lastname FROM employees e WHERE NOT EXISTS (SELECT 1 FROM employees r WHERE r.managerid = e.employeeid); This unnests to an ordinary anti-join and ignores NULL managerid values. Alternatively, add WHERE managerid IS NOT NULL to the subquery.
Exercise
In a plan, a correlated subquery appears as a FILTER step. Name two reasons Oracle might not have unnested it, and one way to find out how many times the subquery ran.
Show answer
Possible reasons include a NOUNNEST hint, a subquery that cannot be proven equivalent as a join (for example one using ROWNUM, or a condition combined with OR), a scalar subquery in the SELECT list, or a cost estimate that favors the filter. To see how many times it ran, run the statement with the GATHERPLANSTATISTICS hint and display the plan with DBMSXPLAN.DISPLAY_CURSOR using the ALLSTATS LAST format. The Starts column shows the number of executions of the subquery step.