skip to content

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.sql
  1. 1SELECT name, price
  2. 2FROM products
  3. 3WHERE price > (SELECT avg(price) FROM products);

where a value goes: in a comparison. the subquery must return one row with one column. this is a scalar subquery.

step 1/4
step through four places a subquery can go. what the subquery has to return depends on where it is: one value, a table, a list, or one value per outer row.

scalar subqueries: one value

the products that cost more than the average product:

sqldb=shop
SELECT round(avg(price), 2) AS avg_price FROM products;
 
SELECT count(*) AS above_average
FROM products
WHERE price > (SELECT avg(price) FROM products);
output, from postgres 18.6
#1 · SELECT 1
avg_pricenumeric
101.39
(1 row)
#2 · SELECT 1
above_averageint8
96
(1 row)

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:

predict the output
sql
SELECT name
FROM products
WHERE price = (SELECT price FROM products WHERE category = 'kitchen');
sqldb=shop
SELECT name
FROM products
WHERE price = (SELECT price FROM products WHERE category = 'kitchen');
output, from postgres 18.6
ERROR 21000: more than one row returned by a subquery used as an expression

zero rows is fine, though. a scalar subquery that finds nothing is NULL:

sqldb=shop
SELECT (SELECT name FROM products WHERE id = 999) AS nobody;
output, from postgres 18.6
SELECT 1
nobodytext
null
(1 row)

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?

sqldb=shop
SELECT count(*) AS regulars
FROM (SELECT customer_id, count(*) AS n
      FROM orders
      GROUP BY customer_id) AS c
WHERE n >= 20;
output, from postgres 18.6
SELECT 1
regularsint8
14
(1 row)

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?

sqldb=shop
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;
output, from postgres 18.6
#1 · SELECT 1
sold_with_inint8
199
(1 row)
#2 · SELECT 1
rows_with_joinint8
24942
(1 row)

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:

products
idint4nametextcategorytextpricenumeric
1chef's knifekitchen49.00
3the art of sqlbooks32.00
5studio headphonesaudio129.99
7wooden trainnull24.00
the inner query, for product 1
  1. SELECT round(avg(p2.price), 2) AS category_avg FROM products AS p2 WHERE p2.category = 'kitchen';
category_avgnumeric
88.62
(1 row)

the chef's knife is in kitchen, so the inner query averages kitchen: 88.62. the knife costs 49.00, well under.

product 1/5
real output, postgres 18.6 (PGlite 0.5.12) · correlated
step through the outer rows. for each one, the inner query runs with that row's category filled in. the wooden train has no category, and category = NULL matches nothing, so its average is NULL.
sqldb=shop
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;
output, from postgres 18.6
SELECT 4
idint4nametextpricenumericcategory_avgnumeric
1chef's knife49.0088.62
3the art of sql32.0092.15
5studio headphones129.99119.84
7wooden train24.00null
(4 rows)

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:

show =
actual rows
the plan for the correlated query over every product. the Aggregate under the outer scan is the subquery, and its loops count is 200: once per product.

the same plan as EXPLAIN prints it, where the subquery has its own label, SubPlan 1:

sqldb=shop
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;
output, from postgres 18.6
EXPLAIN
Seq Scan on products p (actual rows=200.00 loops=1) SubPlan 1 -> Aggregate (actual rows=1.00 loops=200) -> Seq Scan on products p2 (actual rows=20.61 loops=200) Filter: (category = p.category) Rows Removed by Filter: 179

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.