Sub topic 2
Correlated subqueries: the inner query that depends on the outer row
This chapter assumes you know SELECT, WHERE, ORDER BY, INNER JOIN, LEFT JOIN, table aliases, aggregate functions such as AVG, and NULL as a missing value.
A subquery is a query written inside another query. An uncorrelated subquery can run independently. A correlated subquery refers to a column from the outer query, so the inner query depends on the current outer row.
Consider this query:
SELECT c.customer_id, c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.customer_id
);The outer query considers one customer at a time. For that customer, the inner query searches orders. The condition o.customer_id = c.customer_id is the correlation. The inner query uses c.customer_id, which belongs to the outer query.
How correlation works
You can read the query as a question for each customer:
- Take the current customer.
- Search for orders belonging to that customer.
- Keep the customer if the inner query finds at least one row.
This is a logical model. The database might optimize the query into a join or another plan instead of literally running the inner query from scratch for every row.
A correlated subquery can also return a value. In this example, the subquery calculates the average order total for the current customer:
SELECT o.order_id, o.customer_id, o.total
FROM orders AS o
WHERE o.total > (
SELECT AVG(o2.total)
FROM orders AS o2
WHERE o2.customer_id = o.customer_id
);The aliases are important. o represents the outer order. o2 represents rows searched by the inner query. The condition o2.customer_id = o.customer_id makes the average specific to the current order's customer.
The subquery is a scalar subquery because it must produce one value. AVG produces one value for each customer. If a scalar subquery returns multiple rows, many SQL systems report an error. If a customer has no matching orders, AVG usually returns NULL, and the comparison with NULL is not true.
Correlation with `EXISTS`
EXISTS asks whether the subquery returns at least one row. It does not return the matching rows or count them. It only produces a true or false result for the outer row.
The value after SELECT is therefore not important:
SELECT c.customer_id, c.name
FROM customers AS c
WHERE EXISTS (
SELECT o.order_id
FROM orders AS o
WHERE o.customer_id = c.customer_id
);SELECT 1 is a common convention because it shows that the selected value is irrelevant. The correlation condition is what matters.
A correlated subquery in the `SELECT` list
A correlated subquery does not have to appear in WHERE. It can calculate a value for each output row:
SELECT c.customer_id,
c.name,
(
SELECT MAX(o.order_date)
FROM orders AS o
WHERE o.customer_id = c.customer_id
) AS last_order_date
FROM customers AS c;This returns one customer row at a time and calculates that customer's latest order date. A customer with no orders receives NULL.
Use this form when the result needs one related value. For several related values, a grouped query or a join may be clearer and easier to optimize.
Common errors
- Forgetting the correlation condition: Without
o.customer_id = c.customer_id, every customer is tested against all orders. - Using the wrong alias: If both sides accidentally refer to the inner alias, the condition may become
o.customer_id = o.customer_id, which is usually true for non-NULLvalues. - Expecting one row from a multi-row subquery: Use an aggregate such as
MAXorAVG, or useEXISTSwhen only presence matters. - Ignoring
NULL: Comparisons withNULLproduceUNKNOWN, not true. Check whether missing values need separate handling. - Skipping indexes: An index on the correlated column, such as
orders.customer_id, can make each lookup much faster.
CREATE INDEX idx_orders_customer_id
ON orders (customer_id);The best choice depends on the question. Use a correlated EXISTS when the question is “does at least one related row exist?” Use a scalar correlated subquery when each outer row needs one calculated related value. Use a join or grouped query when you need columns from many related rows.
Exercise
In the average-order query, what does o2.customer_id = o.customer_id do?
Show answer
It limits the inner AVG calculation to orders belonging to the customer of the current outer order.