Queries inside queries
“Products that cost more than the average product.” You might try WHERE price > avg(price), but aggregates aren’t allowed in WHERE: it runs on single rows, before anything is averaged.
Instead, put a whole query in parentheses where the value should go. That’s a subquery. The database runs it first and uses its result:
SELECT name, price
FROM products
WHERE price > (SELECT avg(price) FROM products);Subqueries can go in four places:
| Where | It returns | Example |
|---|---|---|
WHERE x > (…) or in SELECT | one value | above the average price |
WHERE x IN (…) | a list of values | customers who ordered this week |
FROM (…) AS name | a table, which needs a name | totals per customer, then filtered |
WHERE EXISTS (…) | true or false | products that were ever ordered |
A subquery can also refer to the outer row. This one runs once for each customer, using that customer’s c.id:
SELECT c.name,
(SELECT count(*) FROM orders o WHERE o.customer_id = c.id) AS orders
FROM customers c;That’s called a correlated subqueryCorrelated subqueryA subquery that refers to a column of the outer query, so it is evaluated once per outer row.Open in glossary →. It’s easy to read, but “once per row” can be slow on big tables; a join with GROUP BY usually does the same work in one pass.
- Kinds: scalar (one row, one column; zero rows give NULL, two rows are a runtime error), row, table (derived table, needs an alias except in PostgreSQL 16+), and predicate subqueries (
IN,EXISTS,ANY/ALL). - Correlated vs uncorrelated: uncorrelated ones run once (an InitPlan in PostgreSQL’s
EXPLAIN). Correlated ones are evaluated per outer row (a SubPlan) unless the planner rewrites them:EXISTS/INbecome semi- and anti-joins, but scalar subqueries in theSELECTlist are generally not decorrelated by PostgreSQL. With an index on the inner column it’s an index probe per row, fine for a page of 50, painful for a report over a million rows. - Rewrites: per-row aggregates → join to a grouped derived table, or
LEFT JOIN LATERALfor top-N per row. “Above the group average” → window functionavg() OVER (PARTITION BY …). INvsEXISTS: equivalent for semi-joins in modern planners; the real difference isNOT INwith NULLs (it returns nothing).= ANY (array)is PostgreSQL’s way to bind a list as one parameter:WHERE id = ANY($1).- Readability: deeply nested derived tables read inside-out. Move steps into CTEs.
Predict the output
Ana has two orders; Ben has none. What does this query do?
SELECT c.name,
(SELECT o.id FROM orders o WHERE o.customer_id = c.id) AS order_id
FROM customers c
WHERE c.name IN ('Ana', 'Ben');A subquery used as a single value must return at most one row. For Ana it returns two, and PostgreSQL stops with 'more than one row returned by a subquery used as an expression'. Ben's zero rows would be fine (NULL). Ask for exactly one value: (SELECT max(o.id) …) or (… ORDER BY o.created_at DESC LIMIT 1).
-- customers who ordered in the last 7 days
SELECT id, name FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE created_at >= now() - interval '7 days');
-- products that were never ordered
SELECT id, name FROM products p
WHERE NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.product_id = p.id);
-- a derived table: customers who spent more than 500, from a grouped subquery
SELECT c.name, t.spent
FROM (SELECT customer_id, sum(total) AS spent
FROM orders WHERE status = 'PAID'
GROUP BY customer_id) AS t
JOIN customers c ON c.id = t.customer_id
WHERE t.spent > 500;The average that isn’t allowed there
Tap the line with the bug.
SELECT id, customer_id, total
FROM orders
WHERE status = 'PAID'
AND total > avg(total)
ORDER BY total DESC;Hint: When does WHERE run, and when are aggregates computed?
PostgreSQL stops with “aggregate functions are not allowed in WHERE”. WHERE looks at one order at a time, before any averaging happens, so there’s no average to compare with yet.
Compute the average in a subquery, which runs on its own and returns one number:
SELECT id, customer_id, total
FROM orders
WHERE status = 'PAID'
AND total > (SELECT avg(total) FROM orders WHERE status = 'PAID')
ORDER BY total DESC;Note the WHERE status = 'PAID' inside the subquery too: “bigger than usual” should compare with the average paid order, not the average of all orders including cancelled ones.
Deep diveA correlated subquery per row, and how to turn it into a joinInterview favorite
An admin list shows customers with their order count and last order date:
SELECT c.id, c.name,
(SELECT count(*) FROM orders o WHERE o.customer_id = c.id) AS orders,
(SELECT max(created_at) FROM orders o WHERE o.customer_id = c.id) AS last_order
FROM customers c
ORDER BY c.name;EXPLAIN shows two SubPlans executed for every customer: 200,000 customers mean 400,000 index probes. For a page of 50 with LIMIT that’s fine. For the CSV export of all customers it takes minutes.
Aggregate once and join:
SELECT c.id, c.name, COALESCE(s.orders, 0) AS orders, s.last_order
FROM customers c
LEFT JOIN (
SELECT customer_id, count(*) AS orders, max(created_at) AS last_order
FROM orders GROUP BY customer_id
) s ON s.customer_id = c.id
ORDER BY c.name;One scan of orders, one hash join. Points worth making: LEFT JOIN plus COALESCE keeps customers without orders at 0 (the scalar subquery gave 0 for count and NULL for max automatically); the per-row form can still win with a small LIMIT on an indexed outer query, because it avoids aggregating all orders; and LATERAL gives you the per-row shape explicitly when you want it.
- Scalar subquery: ≤ 1 row (0 → NULL, 2 → error). Derived tables need an alias (optional in PostgreSQL 16+).
- Uncorrelated = once (InitPlan); correlated = per outer row (SubPlan).
EXISTS/INbecome semi/anti-joins; scalar subqueries inSELECTusually don’t. - Rewrite per-row aggregates as a grouped derived table +
LEFT JOIN, orLATERALfor top-N. NOT IN+ NULL returns nothing;= ANY($1)binds a list.
Check this part
How do you find products priced above the average price?
What makes a subquery correlated?
A scalar subquery in SELECT matches no rows for some outer row. What do you get?
Two scalar subqueries per customer make an export slow. Usual fix?