Sub topic 7
Correlated Subqueries
A correlated subquery is an inner query that refers to a column of the outer query. This chapter explains how Oracle evaluates one, shows the patterns where you will use it, and covers the errors that come up most often.
This chapter assumes you can write basic SELECT, WHERE and GROUP BY queries, join two tables, use aggregates such as AVG and COUNT, and know the HR sample schema (EMPLOYEES and DEPARTMENTS). It also assumes you have read the earlier chapters on single-row subqueries and scalar subqueries.
Uncorrelated versus correlated
An uncorrelated subquery does not depend on the outer query. Oracle can run it once and reuse the result. This query finds employees paid more than the company-wide average:
SELECT first_name, last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);Suppose you want each employee compared with the average of their own department. The inner query's answer now changes from row to row, so it cannot be computed once. The inner query must see the department of the current outer row:
SELECT e.employee_id, e.last_name, e.salary, e.department_id
FROM employees e
WHERE e.salary > (SELECT AVG(i.salary)
FROM employees i
WHERE i.department_id = e.department_id);The reference e.department_id inside the subquery is the correlation. It points to the outer table alias e. Without it, the subquery would be uncorrelated.
The mental model
Think of a correlated subquery as a loop:
- Take the first candidate row from the outer query.
- Pass its correlated column values into the inner query.
- Run the inner query and get a result.
- Use that result to keep or discard the outer row.
- Move to the next outer row and repeat.
This is the logical model. It tells you what the result must be. The optimizer is free to execute the query differently as long as the result is the same. A later chapter covers how it does that.
Aliases and scope rules
Correlated subqueries depend on name resolution, so aliases matter.
- A subquery can see columns of every enclosing query. An outer query cannot see columns of a subquery.
- Oracle resolves an unqualified column name in the innermost query first. If the inner table has a column with that name, it wins, even if you meant the outer one.
- Always give each table an alias and qualify every column in a correlated subquery.
When both the outer and inner query use the same table, as above, the aliases e and i are what make the query readable. Without them the reference would be ambiguous.
Correlated subqueries in the SELECT list
A scalar subquery in the SELECT list is often correlated. It must return one column and at most one row.
SELECT d.department_name,
(SELECT COUNT(*)
FROM employees e
WHERE e.department_id = d.department_id) AS headcount
FROM departments d;Every department appears in the result. A department with no employees gets a headcount of 0, because COUNT(*) returns 0 over zero rows. If you had used an inner join with GROUP BY, those departments would disappear.
If the subquery can return more than one row, Oracle raises an error:
-- ORA-01427: single-row subquery returns more than one row
SELECT d.department_name,
(SELECT e.last_name
FROM employees e
WHERE e.department_id = d.department_id) AS employee
FROM departments d;Fix it by making the subquery return one row, for example with an aggregate such as MAX, or by choosing a different structure, such as a join.
When the subquery finds no row at all, a scalar subquery returns NULL, not an error. So a scalar subquery in the SELECT list that uses a non-aggregate column behaves like a left outer join for the missing rows.
Correlated subqueries with EXISTS
EXISTS is true when the subquery returns at least one row. It is the most natural partner of correlation, because the question "does a related row exist for this outer row?" is a correlated question.
SELECT d.department_name
FROM departments d
WHERE EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id);
SELECT d.department_name
FROM departments d
WHERE NOT EXISTS (SELECT 1
FROM employees e
WHERE e.department_id = d.department_id);The first query lists departments that have at least one employee. The second lists departments with none. The columns in the subquery's SELECT list do not matter, so SELECT 1 is a convention. Oracle stops as soon as it finds one matching row, so EXISTS does not need to read all matches.
Correlated subqueries versus NOT IN
A correlated NOT EXISTS is also the safe way to write "rows with no match". The NOT IN version can silently return nothing when the subquery produces a NULL:
-- Returns no rows: MANAGER_ID contains a NULL (the top-level employee),
-- so NOT IN evaluates to unknown for every row.
SELECT last_name
FROM employees
WHERE employee_id NOT IN (SELECT manager_id FROM employees);
-- Employees who manage nobody, written safely:
SELECT e.last_name
FROM employees e
WHERE NOT EXISTS (SELECT 1
FROM employees r
WHERE r.manager_id = e.employee_id);NOT IN expands into a chain of <> comparisons joined by AND. One comparison with NULL is unknown, and an AND chain with an unknown can never be true. NOT EXISTS only asks whether a row is found, so NULLs in the inner table do not affect it.
Correlated subqueries in DML
A correlated subquery in the WHERE clause of an UPDATE or DELETE applies the same per-row logic to the rows being changed.
UPDATE employees e
SET e.salary = e.salary * 1.05
WHERE e.salary < (SELECT AVG(i.salary)
FROM employees i
WHERE i.department_id = e.department_id);Oracle determines which rows qualify using the data as it was when the statement began. The averages do not drift as rows are updated during the statement, so the result does not depend on the order in which rows are processed.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| ORA-01427: single-row subquery returns more than one row | A scalar subquery or `=` comparison matched several rows | Aggregate, add a filter that makes one row, or use IN or a join |
| ORA-00904: invalid identifier | The correlation reaches too far, for example from a subquery inside an inline view to a table outside it | Use LATERAL or CROSS APPLY, or restructure the query |
| Query returns every row, or no change in results | Missing alias, so the inner column shadows the outer one | Qualify every column with an alias |
| NOT IN returns zero rows | NULL in the subquery result | Use NOT EXISTS, or add `IS NOT NULL` to the subquery |
| Query is very slow on large tables | The inner query runs many times with no supporting index | Index the correlated column, or rewrite as a join |
The ORA-00904 case deserves a note. In Oracle, a correlated reference in a subquery nested inside a FROM-clause inline view cannot refer to tables that are siblings in the same FROM clause. LATERAL and CROSS APPLY, covered in a later chapter, exist to lift this limit.
Performance considerations
The loop model suggests a cost. If the outer query yields N rows and the inner query costs M each, the work is roughly N times M. That is acceptable for a small outer result and a cheap, indexed inner query. It is a problem when both sides are large.
Three practical rules follow:
- Index the column used in the correlation, here
employees.department_id, so each inner execution is an index lookup and not a full scan. - Filter the outer query as much as possible, so fewer rows enter the loop.
- Check the execution plan. Oracle often rewrites correlated subqueries into joins, such as semi-joins for EXISTS and anti-joins for NOT EXISTS. When it does, the loop model no longer describes the real execution.
You can compare an equivalent join with an inline view that aggregates once:
SELECT e.employee_id, e.last_name, e.salary, e.department_id
FROM employees e
JOIN (SELECT department_id, AVG(salary) AS avg_sal
FROM employees
GROUP BY department_id) a
ON a.department_id = e.department_id
WHERE e.salary > a.avg_sal;This version computes each department's average once and joins it. It returns the same rows as the correlated version for employees who have a department. The correlated version is shorter and states the intent directly. The join version shows more clearly that the averages are computed once. Read the plan before deciding that one is faster.
A note on NULL correlation values
A correlation on a column that contains NULL never matches, because NULL = NULL is unknown. In the HR schema, an employee with no department has a NULL department_id. For that employee, the inner query in the department-average example finds no rows, AVG returns NULL, and salary > NULL is unknown, so the employee is excluded. If you want such rows treated differently, handle them explicitly, for example with NVL or an extra condition.
Exercise
Write a query that lists the employees who earn the highest salary in their own department, using a correlated subquery and no GROUP BY in the outer query. Then say why the comparison operator you chose is safe.
Show answer
SELECT e.lastname, e.departmentid, e.salary FROM employees e WHERE e.salary = (SELECT MAX(i.salary) FROM employees i WHERE i.departmentid = e.departmentid); The subquery contains an aggregate with no GROUP BY, so it always returns exactly one row for each outer row, and the = operator is safe. Ties are all returned, because each tied employee equals the maximum. Employees with a NULL department_id are excluded, since the correlation never matches.
Exercise
A colleague wrote: SELECT departmentname FROM departments WHERE departmentid NOT IN (SELECT department_id FROM employees); and it returns no rows, although you know some departments have no employees. What is the likely cause, and how do you rewrite the query as a correlated subquery?
Show answer
At least one employee has a NULL departmentid, so the subquery result contains a NULL and NOT IN evaluates to unknown for every row. Rewrite it with NOT EXISTS: SELECT d.departmentname FROM departments d WHERE NOT EXISTS (SELECT 1 FROM employees e WHERE e.departmentid = d.departmentid); Adding WHERE department_id IS NOT NULL to the original subquery would also work.