subqueries
a query wherever a value or a table can go. scalar, table and correlated subqueries.
- address
- everything.joins.subqueries
- part
- part 3, joins and subqueries
- chapter
- chapter 6 of 11
- reading time
- 8 min
a subquery is a SELECT in parentheses, and it can go anywhere a value or a table can. a scalar subquery returns one value. a table subquery returns rows, for FROM or for IN. a correlated subquery refers to the outer row, so it gets a new answer for every row.
the picture
you know how you sometimes run one query, copy the number it gives you, and paste it into the next one? "what's the average price? 101.39. ok, which products cost more than 101.39?" a subquery is that, without the copy and paste: the first query goes inside the second, in parentheses, right where the number went.
think of a sticky note with a little calculation on it, stuck onto a form where a value is supposed to go. the form doesn't care whether you wrote the number in or stuck a note there. postgres doesn't either: a subquery is just a way to say "the value (or the table) this query produces".
scalar subqueries: one value
the products that cost more than the average product:
SELECT round(avg(price), 2) AS avg_price FROM products;
SELECT count(*) AS above_average
FROM products
WHERE price > (SELECT avg(price) FROM products);| avg_pricenumeric |
|---|
| 101.39 |
| above_averageint8 |
|---|
| 96 |
the subquery runs once, comes back as one number, and the comparison uses it like a constant. a scalar subquery has to return at most one row with exactly one column, and postgres checks the row part while it runs:
SELECT name
FROM products
WHERE price = (SELECT price FROM products WHERE category = 'kitchen');SELECT name
FROM products
WHERE price = (SELECT price FROM products WHERE category = 'kitchen');zero rows is fine, though. a scalar subquery that finds nothing is NULL:
SELECT (SELECT name FROM products WHERE id = 999) AS nobody;| nobodytext |
|---|
| null |
table subqueries: in FROM
a subquery in FROM is a table that exists for one query, often called a derived table. it's how you filter on something that only exists after a GROUP BY, without HAVING, or stack one aggregate on top of another. how many customers have placed 20 orders or more?
SELECT count(*) AS regulars
FROM (SELECT customer_id, count(*) AS n
FROM orders
GROUP BY customer_id) AS c
WHERE n >= 20;| regularsint8 |
|---|
| 14 |
the inner query makes one row per customer with their order count, the outer query counts the rows where that's 20 or more. AS c names the derived table. postgres 16 made that name optional pg 16+, but most other databases still require one, and you'll want it the moment you join the derived table to anything. it's also exactly the "aggregate first" shape that fixes a fan-out.
IN: a list from a query
x IN (subquery) is true when x equals at least one value the subquery returns. which products have ever been sold?
SELECT count(*) AS sold_with_in
FROM products
WHERE id IN (SELECT product_id FROM order_items);
SELECT count(*) AS rows_with_join
FROM products AS p
JOIN order_items AS oi ON oi.product_id = p.id;| sold_with_inint8 |
|---|
| 199 |
| rows_with_joinint8 |
|---|
| 24942 |
199 products, against 24,942 rows for the join. IN asks a yes-or-no question per product, so each product comes back once at most, however many order lines mention it. a join returns one row per matching pair. that difference has a name, the semi join, and a chapter: EXISTS, semi joins and anti joins. its evil twin, NOT IN, has a chapter of its own for a reason.
correlated subqueries: a value per row
the subqueries so far could run once on their own. this one can't: it mentions p.category, a column of the outer query, so it has no answer until it knows which outer row it's for. each product, next to the average price of its own category:
| idint4 | nametext | categorytext | pricenumeric | |
|---|---|---|---|---|
| 1 | chef's knife | kitchen | 49.00 | |
| 3 | the art of sql | books | 32.00 | |
| 5 | studio headphones | audio | 129.99 | |
| 7 | wooden train | null | 24.00 |
- SELECT round(avg(p2.price), 2) AS category_avg FROM products AS p2 WHERE p2.category = 'kitchen';
| category_avgnumeric |
|---|
| 88.62 |
the chef's knife is in kitchen, so the inner query averages kitchen: 88.62. the knife costs 49.00, well under.
category = NULL matches nothing, so its average is NULL.SELECT p.id, p.name, p.price,
(SELECT round(avg(p2.price), 2)
FROM products AS p2
WHERE p2.category = p.category) AS category_avg
FROM products AS p
WHERE p.id IN (1, 3, 5, 7)
ORDER BY p.id;| idint4 | nametext | pricenumeric | category_avgnumeric |
|---|---|---|---|
| 1 | chef's knife | 49.00 | 88.62 |
| 3 | the art of sql | 32.00 | 92.15 |
| 5 | studio headphones | 129.99 | 119.84 |
| 7 | wooden train | 24.00 | null |
p2 is a second alias for products, so the inner query's products and the outer query's products can be told apart. that's a self join's trick, used inside a subquery.
"runs once per row" isn't a figure of speech. here's the plan for all 200 products:
the same plan as EXPLAIN prints it, where the subquery has its own label, SubPlan 1:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT p.id, p.name, p.price,
(SELECT round(avg(p2.price), 2)
FROM products AS p2
WHERE p2.category = p.category) AS category_avg
FROM products AS p;200 outer rows, 200 runs of the inner query, each scanning all 200 products again. that's fine for 200 rows and painful for 2 million. postgres can often rewrite IN and EXISTS subqueries into joins on its own, but a scalar subquery in the select list like this one usually stays a SubPlan. how subqueries get planned has the details, and the usual fix is the one from fan-out: aggregate once per category in a derived table, then join to it.
keylines
- a subquery is a SELECT in parentheses, wherever a value or a table can go.
- scalar subqueries return one value: more than one row is an error, zero rows is NULL.
- a subquery in FROM is a derived table. IN takes a one-column list.
- a correlated subquery uses the outer row, so it gets a new answer per row.
- unqualified names in a subquery can silently resolve to the outer query.