Sub topic 14
How the Optimizer Treats Subqueries
Prerequisites and the working model
Assume you know SELECT, joins, GROUP BY, aggregate functions, and the Oracle HR sample schema. A subquery describes a result that another query uses. The Oracle optimizer then chooses a physical execution plan for that logical request.
The SQL text does not guarantee that Oracle runs the inner query first, or once for every outer row. The optimizer may transform a subquery into a join, move predicates, or calculate a result in another order. These transformations preserve the query's meaning while trying to reduce work.
Unnesting a subquery
Unnesting converts a nested subquery into a join-like operation. For example, this query asks for departments that have at least one employee earning more than 10,000:
SELECT d.department_name
FROM departments d
WHERE d.department_id IN
(SELECT e.department_id
FROM employees e
WHERE e.salary > 10000);Oracle may execute this as a semijoin. A semijoin returns rows from the first input when a match exists, without returning duplicate department rows for every matching employee. The result is logically equivalent to the IN condition.
An EXISTS condition often has the same semijoin opportunity:
SELECT d.department_name
FROM departments d
WHERE EXISTS
(SELECT 1
FROM employees e
WHERE e.department_id = d.department_id
AND e.salary > 10000);The SELECT 1 value is irrelevant. EXISTS only tests whether at least one row qualifies.
When Oracle keeps the subquery
Oracle may leave a subquery nested when transformation would change the result, add complexity, or cost more than the original strategy. Correlation, aggregation, DISTINCT, set operators, and certain outer-join or NULL conditions can affect unnesting.
A correlated subquery is logically evaluated with values from an outer row. However, Oracle can sometimes transform it into a join and aggregate operation. Therefore, do not judge performance from the word “correlated” alone.
Scalar subqueries can also be evaluated repeatedly, cached, or transformed depending on the query and data. A scalar subquery must still return no more than one row. Otherwise Oracle raises ORA-01427: single-row subquery returns more than one row.
Inspecting the chosen plan
Use EXPLAIN PLAN to inspect a possible plan:
EXPLAIN PLAN FOR
SELECT d.department_name
FROM departments d
WHERE EXISTS (
SELECT 1
FROM employees e
WHERE e.department_id = d.department_id
AND e.salary > 10000
);
SELECT *
FROM TABLE(DBMS_XPLAN.DISPLAY);Look for operations such as HASH JOIN SEMI, NESTED LOOPS SEMI, or HASH JOIN ANTI. A semijoin commonly represents EXISTS or IN; an antijoin commonly represents NOT EXISTS or a safely transformed NOT IN.
| SQL construct | Possible plan operation | Meaning |
|---|---|---|
| `EXISTS` or `IN` | Semijoin | Return an outer row when a match exists |
| `NOT EXISTS` | Antijoin | Return an outer row when no match exists |
| Correlated aggregate | Join plus aggregation | Compute grouped values and compare them |
Choosing a technique
Write the clearest correct SQL first. Prefer EXISTS when you are testing for the presence of related rows, especially when the subquery could produce duplicates. Prefer IN when you are naturally comparing a value with a set. Use WITH or an inline view when naming an intermediate result makes the query easier to read or reuse.
Remember that NOT IN has special NULL behavior. A nullable value in its subquery can prevent rows from satisfying the condition. NOT EXISTS is usually the safer anti-match expression.
Exercise
Does a correlated subquery always execute once for every outer row?
Show answer
No. That is its logical meaning, but Oracle may unnest or otherwise transform it into a join, semijoin, or aggregate plan.