Sub topic 2
Correlated subqueries: the inner query that depends on the outer row
This chapter assumes you can write SELECT queries with WHERE and ORDER BY, use INNER JOIN and LEFT JOIN, apply aggregates such as COUNT and AVG, give tables aliases, and treat NULL as a missing value. You should also know that a subquery in WHERE is a query nested inside another query.
From plain subqueries to correlated ones
A plain (uncorrelated) subquery does not depend on the outer query. The database can run it once, take its result, and use that result in the outer query.
SELECT order_id, total
FROM orders
WHERE total > (SELECT AVG(total) FROM orders);The inner query returns one number, the average over all orders. Nothing in it refers to the outer row, so it could be run on its own.
A correlated subquery is different. It refers to a column of the outer query, so its result can change from one outer row to the next. You cannot run it alone, because it has a name in it that only the outer query defines.
SELECT o.order_id, o.customer_id, o.total
FROM orders o
WHERE o.total > (
SELECT AVG(o2.total)
FROM orders o2
WHERE o2.customer_id = o.customer_id
);This returns orders whose total is above the average total of the same customer's orders. The reference o.customer_id inside the inner query is the correlation. It ties the inner query to the current outer row.
The logical evaluation model
The easiest way to read a correlated subquery is as a loop:
- Take one row from the outer query.
- Substitute that row's values wherever the inner query mentions the outer alias.
- Run the inner query with those values.
- Use the inner result in the outer condition to keep or discard the row.
- Move to the next outer row.
This is a logical model. It tells you what the result must be, not how the database computes it. Optimizers often turn a correlated subquery into a join or a hash lookup, so it does not always run once per row. Section "Execution and indexing" below returns to this. For now, use the loop to reason about correctness.
A worked trace
Suppose orders holds these rows.
| order_id | customer_id | total |
|---|---|---|
| 1 | 10 | 100 |
| 2 | 10 | 300 |
| 3 | 20 | 50 |
| 4 | 20 | 50 |
For order 1, the inner query averages the totals for customer 10: (100 + 300) / 2 = 200. The test is 100 > 200, which is false, so order 1 is dropped. For order 2, the average is again 200, and 300 > 200 is true, so order 2 is kept. For orders 3 and 4, customer 20's average is 50, and 50 > 50 is false, so both are dropped. The result is order 2 only.
Note that each customer has its own average. A plain subquery could only give one average for the whole table.
Aliases and scope rules
Correlation depends on name resolution, so aliases matter.
- An inner query can see the tables in its own FROM clause and the tables of every enclosing query.
- An outer query cannot see the tables inside a subquery.
- When a name exists in both the inner and outer scopes, the innermost scope wins.
The last rule causes a classic bug. Suppose you write the subquery without aliases:
SELECT order_id
FROM orders
WHERE total > (
SELECT AVG(total)
FROM orders
WHERE customer_id = customer_id
);Here customer_id = customer_id resolves both names to the inner orders. The condition is true for every inner row (except rows where it is NULL), so the subquery computes the global average. The query runs without error and returns wrong results. The fix is to alias the two copies of the table (o and o2) and qualify every column that could be ambiguous.
Correlation can sit in different places
The correlated reference usually appears in the inner WHERE clause, but the inner query can be used in several positions of the outer query.
| Position | Typical use |
|---|---|
| WHERE with a comparison | Compare a row to a value computed from its related rows |
| WHERE with EXISTS or NOT EXISTS | Test whether related rows are present or absent |
| WHERE with IN or ANY | Test membership in a related set |
| SELECT list | Return one computed value per outer row |
Here is a correlated scalar subquery in the SELECT list:
SELECT c.customer_id, c.name,
(SELECT MAX(o.order_date)
FROM orders o
WHERE o.customer_id = c.customer_id) AS last_order_date
FROM customers c;For each customer, the inner query finds the latest order date. For a customer with no orders, MAX over zero rows returns NULL, so last_order_date is NULL. The outer query still returns that customer. This is different from an inner join, which would drop the customer.
The scalar rule
When a subquery is used where a single value is expected (a comparison or the SELECT list), it must return at most one row and one column. If it returns zero rows, the value is NULL. If it returns more than one row, most databases raise an error such as "subquery returned more than one value".
An aggregate without GROUP BY always returns exactly one row, which is why AVG and MAX are the usual choice here. A query like this is risky:
SELECT c.customer_id,
(SELECT o.order_date
FROM orders o
WHERE o.customer_id = c.customer_id) AS order_date
FROM customers c;It works while every customer has at most one order and fails as soon as one has two. The failure depends on the data, so it can appear in production long after testing.
Correlation with other predicates
The correlation condition does not have to be an equality. Any condition that mentions the outer row creates correlation. For example, this query finds each order and the number of earlier orders by the same customer:
SELECT o.order_id,
o.customer_id,
(SELECT COUNT(*)
FROM orders o2
WHERE o2.customer_id = o.customer_id
AND o2.order_date < o.order_date) AS earlier_orders
FROM orders o;The inner query has two correlated conditions. One matches the customer, and one restricts to earlier dates. COUNT(*) over zero rows returns 0, not NULL, so a first order shows 0 earlier orders. Remember this difference: COUNT returns 0 for no rows, while AVG, SUM, MAX, and MIN return NULL.
NULL in the correlation column
An equality such as o2.customer_id = o.customer_id is UNKNOWN when either side is NULL, and WHERE keeps only rows where the condition is TRUE. So an outer row with a NULL customer_id matches no inner rows. For the average example above, the subquery returns NULL for such an order, total > NULL is UNKNOWN, and the order is dropped. If you want NULL customers treated as one group, you must say so explicitly, for example with IS NOT DISTINCT FROM where your database supports it.
Common errors
- Missing correlation. If you forget the link condition, the inner query is uncorrelated and compares every outer row to the same global value. For an existence test, it returns all rows or none.
- Wrong alias. Correlating to the wrong table, such as
o2.customer_id = o2.customer_id, is always true and defeats the correlation. - Scalar subquery returning many rows. Use an aggregate, or add a condition that guarantees a single row, such as a primary key match.
- Using a join result as an aggregate. If you rewrite a correlated aggregate as a join, remember that joining before aggregating can multiply rows. Aggregate in a derived table first, then join.
- Assuming per-row execution. The loop is a logical model. Do not rely on side effects or on the order of evaluation.
Execution and indexing
Databases handle correlated subqueries in one of two broad ways. A simple engine, or a plan in which no rewrite applies, may run the inner query once per outer row. This is called a nested-loop style of execution. A more capable optimizer may decorrelate the query, which means rewriting it as a join or aggregation that computes the answer for all rows at once. Which one you get depends on the database, its version, and the query shape. Use your database's EXPLAIN output to check.
If the inner query does run per outer row, its cost matters a lot. With 100,000 customers and an unindexed orders table, each lookup scans all orders, so the work grows as the product of the two table sizes. An index on the correlation column removes the scan:
CREATE INDEX idx_orders_customer_id ON orders (customer_id);With this index, each inner lookup finds the matching orders directly. For the "later orders" query above, a composite index on (customer_id, order_date) serves both conditions. Put the equality column first and the range column second.
Choosing a correlated subquery
A correlated subquery is a good fit when the question is naturally "for each row, look at its related rows". It reads closer to the question than a join with GROUP BY, and it avoids the row multiplication that joins can cause. It is a weaker fit when the same aggregate is needed for many columns, because each subquery is separate. In that case, compute the aggregates once in a derived table or with a window function, and join to the result.
The chapters that follow build on this idea. EXISTS and NOT EXISTS are correlated subqueries whose only job is to report whether the inner query found a row.
Exercise
Given the table orders(orderid, customerid, order_date, total), write a query that returns every order whose total is the highest among that customer's orders. Then explain what happens for a customer whose orders all have the same total.
Show answer
SELECT o.orderid, o.customerid, o.total FROM orders o WHERE o.total = ( SELECT MAX(o2.total) FROM orders o2 WHERE o2.customerid = o.customerid ); For each outer order, the inner query finds the maximum total for the same customer, and the outer WHERE keeps the order if its total equals that maximum. If all of a customer's orders have the same total, every one of them equals the maximum, so all of that customer's orders are returned. The query returns ties, not a single row per customer.
Exercise
A colleague writes SELECT orderid FROM orders WHERE total > (SELECT AVG(total) FROM orders WHERE customerid = customer_id); and says it returns orders above their own customer's average. Why is that wrong, and how do you fix it?
Show answer
Both customerid names resolve to the inner orders table, because the innermost scope wins. The condition is true for every inner row with a non-NULL customerid, so the subquery computes the global average, not the per-customer average. Fix it with aliases: SELECT o.orderid FROM orders o WHERE o.total > (SELECT AVG(o2.total) FROM orders o2 WHERE o2.customerid = o.customer_id);
Exercise
In the query that returns each customer with their latest order date as a SELECT-list subquery, what value appears for a customer with no orders, and what would a COUNT(*) version of the same subquery return for that customer?
Show answer
The MAX version returns NULL, because MAX over zero rows is NULL. A COUNT(*) version returns 0, because COUNT over zero rows is 0. In both cases the customer still appears in the result, since the subquery is in the SELECT list and does not filter outer rows.