Part 06 / Topic 4 of 8
Correlated subqueries
Every subquery so far ran independently. A correlated subquery references the outer row — conceptually it re-runs for each one. Products priced above their own category's average:
SELECT p.name, p.price, p.category_id
FROM products AS p
WHERE p.price > (
SELECT avg(p2.price) FROM products AS p2
WHERE p2.category_id = p.category_id
)
ORDER BY p.category_id, p.price DESC;
name | price | category_id
--------------------+---------+-------------
Postgres Deep Dive | 55.00 | 2
Laptop Pro 14 | 1200.00 | 4
Phone X | 799.00 | 5
Coffee Maker | 120.00 | 6
(4 rows)
The inner query's p.category_id reaches out to the current outer row — that reach is the correlation. The EXISTS queries you wrote in sections 2–3 were correlated too (o.customer_id = c.customer_id); it's the natural shape for per-row questions.
Mental model: "for each outer row, run the inner question with that row's values plugged in." (The planner usually finds a faster strategy than literally re-running — Stage 4 shows you how to check.)
🧪 Quick quiz — answer from memory, then check.
- What makes a subquery correlated?
- Is
EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)correlated?
Show the answers
- It references a column of the outer query, so its result depends on the current outer row.
- Yes —
c.customer_idis the outer table's column inside the inner query.
Exercise 4: Stars of their category
What to do: Products priced above their own category's average, by category.
Sample output:
name | price | category_id
--------------------+---------+-------------
Postgres Deep Dive | 55.00 | 2
Laptop Pro 14 | 1200.00 | 4
Phone X | 799.00 | 5
Coffee Maker | 120.00 | 6
(4 rows)
💡 Hint: a correlated subquery — the inner average is filtered by the outer row's category_id. (Single-product categories can't beat their own average, so 1 and 3 are absent.)
Show the solution to Exercise 4
-- Exercise 4: Above their own category's average
SELECT p.name, p.price, p.category_id
FROM products p
WHERE p.price > (
SELECT avg(p2.price) FROM products p2
WHERE p2.category_id = p.category_id
)
ORDER BY p.category_id, p.price DESC;