| Lesson 7 | Reading non-correlated subqueries |
| Objective | Identify non-correlated subqueries in Oracle 26ai, distinguish membership from joins, and preserve NULL and duplicate semantics when comparing rewrites. |
The diagram uses the optional HR sample schema. To run its examples, the schema must be installed and you must have access to HR.EMPLOYEES and HR.DEPARTMENTS. The examples are instructional SQL, not recorded results from a database execution.
SELECT e.employee_id
FROM hr.employees e
WHERE e.department_id IN (
SELECT d.department_id
FROM hr.departments d
);
The inner query selects department identifiers using only alias d, which is declared inside that query block. It contains no reference to e, so it is non-correlated. The expression e.department_id to the left of IN belongs to the outer block. Its presence there does not make the inner query correlated.
IN tests whether the outer value equals a member of the inner result. Here, an employee is selected when its department identifier matches a department returned by the subquery. Duplicate matching values in the inner result do not produce additional copies of that employee row. The predicate is a membership test, not an instruction to output every matching pair.
For this simple example, the inner SELECT can also be inspected independently. That is a useful way to understand its result, but it does not prove that Oracle physically runs it separately. SQL states the required relationship; the optimizer determines an eligible implementation.
SELECT e.employee_id
FROM hr.employees e
WHERE EXISTS (
SELECT 1
FROM hr.departments d
WHERE d.department_id = e.department_id
);
The reference e.department_id now appears inside the inner block, although alias e is defined by the outer query. This makes the subquery correlated. Conceptually, the condition asks whether a matching department exists for the current employee. SELECT 1 supplies a constant projection; it does not count departments. EXISTS tests whether the subquery has a row.
These two positive membership forms select the same employee rows for this condition. An employee with a NULL department identifier or no matching department is excluded by both. This is a statement about selected rows, not a promise of identical plans, timings or output ordering. Neither example guarantees ordering without an ORDER BY.
Qualifying columns with aliases makes this distinction visible. An unqualified column name inside a subquery may resolve to an outer block if it is not found in the inner block. A misspelled or misunderstood reference can therefore create unintended correlation. Read each reference against its declaration rather than relying only on indentation.
The next examples retain the lesson's DBA context. They require authorized dictionary-view access in the intended database container. DBA_ROLE_PRIVS describes role grants to users and roles; its GRANTEE identifies the recipient. Comparing grantees with DBA_USERS.USERNAME answers a role-grant membership question.
These queries do not identify direct grants on application tables and do not establish a user's complete effective privileges. Direct object grants involve a different dictionary view, DBA_TAB_PRIVS. Effective access can also involve system privileges, role relationships, PUBLIC and container scope. Treat the following as examples of subquery semantics, not a complete security audit.
SELECT u.username
FROM dba_users u
WHERE u.username NOT IN (
SELECT rp.grantee
FROM dba_role_privs rp
WHERE rp.grantee IS NOT NULL
);
rp, so it is non-correlated.The explicit NULL filter documents the intended anti-membership test. It does not assert that your dictionary currently contains NULL grantees. Usernames are non-null identifiers; removing NULL values from the compared set avoids the general NOT IN issue discussed below. A returned user is not thereby shown to lack all privileges.
SELECT u.username
FROM dba_users u
WHERE u.username IN (
SELECT rp.grantee
FROM dba_role_privs rp
);
NOT IN to IN changes the membership condition, not the reference scope.Use the form that expresses the question you need to answer. There is no rule that non-correlated subqueries should normally use NOT IN, or that IN should always be replaced with a table join. Before comparing alternatives, check whether they preserve both the selected values and their multiplicities.
SELECT u.username
FROM dba_users u
JOIN dba_role_privs rp
ON rp.grantee = u.username;
Suppose, as a hypothetical example, a user has three matching role-grant rows. The ordinary join can return that username three times. The preceding IN query returns the user's outer row once because it asks only whether a match exists. A correlated EXISTS test would likewise avoid multiplying that outer row by the number of matching grants.
For this particular projection of unique usernames, a join with DISTINCT can return the same username set as the membership query:
SELECT DISTINCT u.username
FROM dba_users u
JOIN dba_role_privs rp
ON rp.grantee = u.username;
That does not make DISTINCT a universal repair. If the outer source legitimately contains duplicate projected values, deduplication can remove rows the original membership query preserved. Adding other projected columns also changes the comparison. State the required result first and check equivalence before investigating speed.
Oracle may already transform a membership test into an efficient semijoin. A semijoin preserves the qualifying outer rows without emitting a separate result for every inner match. Writing an explicit ordinary join does not force an improvement, and adding duplicate elimination can introduce work. Measure equivalent alternatives rather than ranking them by appearance.
A single-column NOT IN condition requires the candidate to differ from every value in the compared set. Comparisons with NULL generally produce UNKNOWN. A WHERE clause retains only rows for which its condition is TRUE, so UNKNOWN does not qualify a row.
SELECT 1 AS candidate
FROM dual
WHERE 1 NOT IN (2, NULL);
From SQL semantics, this example selects no row: the comparison with 2 is true, but the comparison with NULL is unknown. This is an explanatory result, not a captured execution. More generally, a NULL returned by the single-column subquery can prevent all outer rows from satisfying NOT IN. Do not overlook nullable inner keys when interpreting an unexpectedly empty result.
There is a separate empty-set case. If the subquery returns no rows, NOT IN is true, including for a NULL outer value. Against a nonempty set, a NULL outer value does not satisfy the ordinary comparisons. This distinction matters when claiming that two anti-membership queries are equivalent.
NOT EXISTS asks whether the matching subquery has no rows. An equality test inside it does not match unrelated NULL inner keys, but a NULL outer key may also find no match and therefore qualify. Consequently, replacing NOT IN with NOT EXISTS is not unconditionally semantics-preserving. Establish the nullability assumptions or define the intended handling explicitly.
Consider an illustrative application schema with AUTHOR(author_key, author_last_name) and BOOK_AUTHOR(author_key, ...). Assume AUTHOR.author_key is a primary key and therefore non-null. The association key may be nullable for this example. These are application tables, not objects guaranteed to exist in Oracle's sample schemas.
SELECT a.author_key, a.author_last_name
FROM author a
WHERE a.author_key NOT IN (
SELECT ba.author_key
FROM book_author ba
WHERE ba.author_key IS NOT NULL
);
This non-correlated subquery supplies a set of non-null author keys with recorded associations. The outer query selects authors whose keys are absent. It establishes absence from BOOK_AUTHOR; calling these authors “unpublished” would require a data model in which that absence reliably represents publication status.
Under the stated non-null outer-key assumption, the following correlated anti-match selects the same author rows:
SELECT a.author_key, a.author_last_name
FROM author a
WHERE NOT EXISTS (
SELECT 1
FROM book_author ba
WHERE ba.author_key = a.author_key
);
The inner reference to a.author_key makes the second query correlated. The first filters NULL inner keys, and the outer primary key cannot be NULL. Those conditions explain why this comparison is valid. Do not generalize the equivalence to queries with nullable outer keys or different projections. Selecting the author key as well as the surname also keeps distinct authors with the same name identifiable.
SELECT e.employee_id, e.salary
FROM hr.employees e
WHERE e.salary > (
SELECT AVG(x.salary)
FROM hr.employees x
);
The inner query computes the overall average salary using alias x. It does not reference e, so it is non-correlated even though both blocks read HR.EMPLOYEES. Sharing a table name is not correlation; referencing an outer column is.
A scalar subquery supplies one column value from at most one row. Zero rows yield NULL; more than one row causes an error. Here, AVG without GROUP BY produces one aggregate row, potentially containing NULL if there are no non-null salaries. When the average is NULL, the outer greater-than comparison is not TRUE. Adding grouping can change scalar cardinality and must be reviewed accordingly.
Use a labeled estimate for the HR membership query. Run the display in the same session and choose a fresh statement label for each comparison.
EXPLAIN PLAN SET STATEMENT_ID = 'L7_IN_01' FOR
SELECT e.employee_id
FROM hr.employees e
WHERE e.department_id IN (
SELECT d.department_id
FROM hr.departments d
);
SELECT *
FROM TABLE(DBMS_XPLAN.DISPLAY(
'PLAN_TABLE', 'L7_IN_01', 'TYPICAL +ALIAS +PREDICATE'
));
EXPLAIN PLAN does not execute the target query. Its rows and costs are estimates, and the executed application cursor can differ. Inspect aliases, predicates and the row-source tree rather than expecting the text's nested structure to appear unchanged in the plan. Do not assume that a named operator must appear on every installation.
For a measured comparison, follow Lesson 6's runtime-statistics procedure: collect statistics during a controlled execution, for example with GATHER_PLAN_STATISTICS, fetch the intended result, and identify the correct SQL ID and child cursor. DBMS_XPLAN.DISPLAY_CURSOR with ALLSTATS LAST displays collected data; it does not collect statistics retroactively.
Compare actual rows with estimates in the context of Starts, and examine buffers and available timing evidence. Use equivalent bind values, result consumption and workload conditions. Check result equivalence before comparing resource use. A lower optimizer cost or a shorter-looking query is not proof of a successful optimization.
The next lesson examines index range scans, another access-path choice whose usefulness depends on the query and measured workload.