Sub topic 6
Correlated subqueries: referencing the outer row
This chapter assumes you can write SELECT, WHERE, and GROUP BY queries and use aggregate functions. It also assumes you know how NULL behaves in comparisons, and that you have seen scalar subqueries and IN subqueries from earlier chapters.
Uncorrelated versus correlated
An uncorrelated subquery can run on its own. The database can evaluate it once and reuse the result. The scalar example salary > (SELECT AVG(salary) FROM employees) is of this kind.
A correlated subquery refers to a column of the outer query. It cannot run on its own, because its result depends on which outer row is being examined. Conceptually, the database evaluates it again for every outer row.
The following query finds employees who earn more than the average of their own department:
SELECT e.name, e.department_id, e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = e.department_id
);The condition e2.department_id = e.department_id is the correlation. e2 belongs to the subquery, and e belongs to the outer query. The subquery can see e, but the outer query cannot see e2. Scope only works inward.
How evaluation works
Use this model to reason about results. The optimizer may execute the query differently, but the result is always the same as this model gives.
- Take the next row from the outer table.
- Substitute that row's values wherever the subquery mentions the outer alias.
- Run the subquery and get its result.
- Use the result in the outer condition. Keep the row only if the condition is true.
- Repeat for the next outer row.
A worked trace
Suppose employees holds these rows:
| name | department_id | salary |
|---|---|---|
| Ana | 10 | 5000 |
| Ben | 10 | 7000 |
| Cara | 20 | 4000 |
| Dev | 20 | 4400 |
| Eli | 30 | 6000 |
The query above evaluates like this:
| Outer row | Subquery average | `salary > average`? |
|---|---|---|
| Ana | 6000 (dept 10) | no |
| Ben | 6000 (dept 10) | yes |
| Cara | 4200 (dept 20) | no |
| Dev | 4200 (dept 20) | yes |
| Eli | 6000 (dept 30, only Eli) | no |
The result is Ben and Dev. The uncorrelated version, which compares against the company average of 5280, would return Ben and Eli. The correlation changes the question from "above the company average" to "above your own department's average."
Choosing aliases and avoiding scope mistakes
Always alias both the outer and the inner table, and qualify every column in a correlated subquery. This avoids the most common error with this feature.
When the database sees an unqualified column name inside a subquery, it looks in the subquery's own tables first. Only if it finds no match there does it look outward. Consider this broken query:
SELECT e.name
FROM employees e
WHERE e.salary > (
SELECT AVG(salary)
FROM employees
WHERE department_id = department_id
);Both department_id references resolve to the inner employees table. The condition compares each inner row with itself, so it is true for every row with a non-null department. The subquery returns the company average, and nothing is correlated. The query runs without error and returns wrong results.
The correlation can live in any clause
The examples so far use the WHERE clause. A correlated scalar subquery can also appear in the SELECT list:
SELECT c.name,
(SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = c.id) AS order_count
FROM customers c;This returns one row for every customer, including customers with no orders, which get 0. It is a concise alternative to a LEFT JOIN with GROUP BY. A later chapter covers this form in more depth.
Common patterns
Compare a row to a per-group aggregate
This is the department average pattern shown above. The same shape works for "the most expensive product in each category" or "orders larger than the customer's own average order."
Pick the latest or largest row per group
SELECT o.id, o.customer_id, o.order_date, o.total
FROM orders o
WHERE o.order_date = (
SELECT MAX(o2.order_date)
FROM orders o2
WHERE o2.customer_id = o.customer_id
);This returns each customer's most recent order. If a customer has two orders on the latest date, both rows are returned. If you need exactly one row per customer, add a tie-breaker such as the highest id, or use a lateral subquery (covered in a later chapter).
Test whether related rows exist
A correlated subquery is the basis of EXISTS and NOT EXISTS, which the next chapter covers. It looks like this:
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);The correlation o.customer_id = c.id is what ties the existence test to each customer.
What happens when the subquery finds nothing
For a correlated scalar subquery in a comparison, an empty inner result matters. The outcome depends on what the subquery returns.
AVG,MIN,MAX, andSUMreturnNULLwhen no rows match. The comparisonsalary > NULLis unknown, so the outer row is discarded.COUNT(*)returns 0 when no rows match, so the comparison works normally.
This explains a subtle effect in the department example. An employee whose department_id is NULL never matches e2.department_id = e.department_id, because NULL = NULL is unknown. The inner query finds no rows, the average is NULL, and the employee is silently left out of the result.
If you want such rows handled differently, say so explicitly, for example with COALESCE around the subquery or an extra OR e.department_id IS NULL branch. Decide what the business question needs, rather than relying on the default.
Errors you are likely to meet
- More than one row returned by a subquery used as an expression. A scalar position such as
salary > (subquery)needs at most one row. If the correlation matches several rows and the subquery has no aggregate, the database raises an error, or in some systems (older MySQL modes, SQLite) uses an arbitrary row. Wrap the value in an aggregate or addLIMIT 1with anORDER BYto make the choice deliberate. - Referencing the outer table from a
FROMsubquery. A plain derived table cannot refer to tables that appear beside it in the sameFROMclause. If you need that, useLATERALwhere your database supports it. - Referencing an inner alias from the outer query. The inner alias is out of scope there. Move the logic into a derived table or a join.
- Same alias in both levels. Reusing
efor both queries makes the innereshadow the outer one. The outer reference then points at the inner table, and you are back to the self-comparison bug above.
Performance
The "run once per outer row" model describes semantics, not necessarily the actual plan. Many optimizers rewrite a correlated subquery into a join or a hash aggregate, so cost may be close to that of an equivalent join. Others execute it as a nested loop, which costs roughly one inner lookup per outer row.
Two practical points follow:
- Index the columns used in the correlation. For the department example, an index on
employees(department_id)makes each inner lookup cheap. For the orders example, indexorders(customer_id), ororders(customer_id, order_date)to serve theMAXlookup directly. - If a correlated subquery is slow on a large table, compare it with a version that computes the aggregate once in a derived table:
SELECT e.name, e.department_id, e.salary
FROM employees e
JOIN (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) AS d ON d.department_id = e.department_id
WHERE e.salary > d.avg_salary;This runs the aggregation once and joins the result. Check both forms with your database's EXPLAIN. Do not assume that either one is faster. The result is the same for these tables, except for the NULL department case, where the inner join also drops those rows.
Summary of the working model
- A correlated subquery references columns from an enclosing query, so it cannot run independently.
- Conceptually it runs once per outer row, with that row's values substituted in.
- Qualify every column with an alias. Unqualified names resolve to the inner table first.
- Empty inner results give
NULLfor most aggregates and 0 forCOUNT. - Index the correlated columns, and compare against a join or derived-table rewrite when performance matters.
Exercise
Write a query that returns the name and total of each order whose total is below the average order total for the same customer. Tables: orders(id, customer_id, total). Then explain what happens to a customer who has only one order.
Show answer
SELECT o.id, o.customerid, o.total FROM orders o WHERE o.total < ( SELECT AVG(o2.total) FROM orders o2 WHERE o2.customerid = o.customer_id ); (The orders table has no name column, so the query returns the order id and customer id. Customer names would need a join to customers.) For a customer with a single order, the inner average equals that order's total, so total < average is false and the order is not returned. A customer with all orders of equal total is excluded the same way.
Exercise
A teammate writes the query below to find employees paid more than the average of their own department. It returns the same rows as the company-wide average comparison. Why, and how do you fix it? SELECT e.name FROM employees e WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE departmentid = departmentid);
Show answer
Inside the subquery, both unqualified departmentid references resolve to the inner employees table, because the database looks in the subquery's own tables first. The condition compares each inner row with itself, so it is true for every row with a non-null departmentid, and the subquery returns the company average. Fix it by aliasing the inner table and qualifying the outer reference: (SELECT AVG(e2.salary) FROM employees e2 WHERE e2.departmentid = e.departmentid).