skip to content

WITH and CTEs

naming a subquery so you can read your own query. inlined by default, MATERIALIZED when you ask.

address
everything.joins.ctes
part
part 3, joins and subqueries
chapter
chapter 11 of 11
reading time
8 min

WITH name AS (query) gives a subquery a name, up front, so the main query can use it like a table and you can read the whole thing top to bottom. that's a CTE (common table expression).

postgres inlines a CTE that's used once, as if you'd written the subquery in place. it materializes one (computes it once, keeps the result) when it's used more than once, or when you write MATERIALIZED.

the picture

you know the query you have to read from the middle out? a subquery inside a JOIN, another one in the WHERE, and inside that one the first subquery again, copied, because it's needed twice. it works. nobody can review it.

think of a recipe. one version says "fold in a sauce made by melting butter, whisking in flour, then adding milk slowly until..." in the middle of step four. the other says, at the top, "make a béchamel: butter, flour, milk", and step four says "fold in the béchamel". same dish. the second one you can follow, and if the sauce is needed twice, you write it down once.

nested.sql
  1. 1SELECT c.name, c.city, p.n
  2. 2FROM customers AS c
  3. 3JOIN (SELECT customer_id, count(*) AS n
  4. 4 FROM orders
  5. 5 GROUP BY customer_id) AS p
  6. 6 ON p.customer_id = c.id
  7. 7WHERE p.n > (SELECT avg(n)
  8. 8 FROM (SELECT customer_id, count(*) AS n
  9. 9 FROM orders
  10. 10 GROUP BY customer_id) AS again)
  11. 11ORDER BY p.n DESC, c.id
  12. 12LIMIT 5;

nested: the per-customer subquery appears twice, once to join against and once, wrapped in another subquery, to average. read it from the inside out.

step 1/2
step through the same question written twice: customers with more orders than the average customer. the nested version has the per-customer count written out twice. the CTE version names it once and uses the name twice.

writing one

the CTE version, for real:

sqldb=shop
WITH per_customer AS (
  SELECT customer_id, count(*) AS n
  FROM orders
  GROUP BY customer_id
)
SELECT c.name, c.city, p.n
FROM per_customer AS p
JOIN customers AS c ON c.id = p.customer_id
WHERE p.n > (SELECT avg(n) FROM per_customer)
ORDER BY p.n DESC, c.id
LIMIT 5;
output, from postgres 18.6
SELECT 5
nametextcitytextnint8
Maya ChenSan Francisco57
Mei KowalskiHamburg36
Grace OkaforLagos33
Zoe MartinLyon31
Zoë MartinParis30
(5 rows)

WITH comes first, before the SELECT. inside the parentheses is any query. after that, per_customer can be used anywhere in the statement where a table could go, as many times as you like. it exists for this one statement and is gone after it. the nested version returns exactly the same rows:

sqldb=shop
SELECT c.name, c.city, p.n
FROM customers AS c
JOIN (SELECT customer_id, count(*) AS n
      FROM orders
      GROUP BY customer_id) AS p
  ON p.customer_id = c.id
WHERE p.n > (SELECT avg(n)
             FROM (SELECT customer_id, count(*) AS n
                   FROM orders
                   GROUP BY customer_id) AS again)
ORDER BY p.n DESC, c.id
LIMIT 5;
output, from postgres 18.6
SELECT 5
nametextcitytextnint8
Maya ChenSan Francisco57
Mei KowalskiHamburg36
Grace OkaforLagos33
Zoe MartinLyon31
Zoë MartinParis30
(5 rows)

a chain of steps

a WITH can hold several CTEs, separated by commas, and each one can use the ones before it. that turns a big query into a list of named steps, like variables in a program:

sqldb=shop
WITH per_customer AS (
  SELECT customer_id, count(*) AS n
  FROM orders
  GROUP BY customer_id
),
regulars AS (
  SELECT customer_id FROM per_customer WHERE n >= 20
),
by_country AS (
  SELECT c.country, count(*) AS regulars
  FROM regulars AS r
  JOIN customers AS c ON c.id = r.customer_id
  GROUP BY c.country
)
SELECT country, regulars
FROM by_country
ORDER BY regulars DESC, country;
output, from postgres 18.6
SELECT 9
countrycharregularsint8
DE3
FR2
IE2
PT2
BR1
CA1
GB1
NG1
US1
(9 rows)

count per customer, keep the regulars, group them by country. each step is small enough to check on its own: select from any one of them and look. that's most of the value of a CTE, and it's why the fan-out fix ("aggregate first, then join") usually ends up written as one.

a CTE that refers to itself is a different animal: a recursive CTE, the query that walks an org chart, in part 4. and a CTE can also hold an INSERT, UPDATE or DELETE with RETURNING, which is in changing data.

inlined by default

does naming a subquery change how it runs? for a CTE used once, no:

predict the output
sql
WITH c AS (SELECT * FROM customers)
SELECT name, city FROM c WHERE id = 42;

ask for MATERIALIZED and that changes. the CTE is computed first, all of it, and the outer query reads the stored result:

show =
actual rows
the same query, inlined and materialized. inlined, the filter reaches the index: one row read. materialized, all 2,000 customers go into the CTE's result first, and the filter throws away 1,999 of them.

the same thing, as EXPLAIN prints it:

sqldb=shop
EXPLAIN (COSTS OFF)
WITH c AS (SELECT * FROM customers)
SELECT name, city FROM c WHERE id = 42;
 
EXPLAIN (COSTS OFF)
WITH c AS MATERIALIZED (SELECT * FROM customers)
SELECT name, city FROM c WHERE id = 42;
output, from postgres 18.6
#1 · EXPLAIN
Index Scan using customers_pkey on customers Index Cond: (id = 42)
#2 · EXPLAIN
CTE Scan on c Filter: (id = 42) CTE c -> Seq Scan on customers

no CTE in the first plan at all: it's just an Index Scan on customers. the second has a CTE c subplan (a Seq Scan of every customer) and a CTE Scan over its result, with the filter applied after.

used twice, computed once

when a CTE is referenced more than once, postgres materializes it by default: compute it once, read the stored result every time it's named. here per_customer is used twice, once for the rows and once for the average:

show =
actual rows
switch between the default and NOT MATERIALIZED. by default, orders is grouped once (the HashAggregate on the left is the CTE, computed one time) and two CTE Scans read its result. NOT MATERIALIZED inlines both uses, so orders is read and grouped twice.

EXPLAIN labels the parts the tree leaves out: CTE per_customer is the one computation, and each CTE Scan on per_customer is a read of its result.

sqldb=shop
EXPLAIN (COSTS OFF)
WITH per_customer AS (
  SELECT customer_id, count(*) AS n FROM orders GROUP BY customer_id
)
SELECT count(*) FROM per_customer
WHERE n > (SELECT avg(n) FROM per_customer);
output, from postgres 18.6
EXPLAIN
Aggregate CTE per_customer -> HashAggregate Group Key: orders.customer_id -> Seq Scan on orders InitPlan 2 -> Aggregate -> CTE Scan on per_customer per_customer_1 -> CTE Scan on per_customer Filter: ((n)::numeric > (InitPlan 2).col1)

and the answer itself:

sqldb=shop
WITH per_customer AS (
  SELECT customer_id, count(*) AS n FROM orders GROUP BY customer_id
)
SELECT count(*) AS above_average, (SELECT round(avg(n), 2) FROM per_customer) AS average_orders
FROM per_customer
WHERE n > (SELECT avg(n) FROM per_customer);
output, from postgres 18.6
SELECT 1
above_averageint8average_ordersnumeric
6815.10
(1 row)

681 customers have more orders than the average of 5.10. the default is usually right for a CTE used twice: grouping 10,000 orders once is cheaper than twice. NOT MATERIALIZED is for the cases where each use can push its own filter into the CTE and make it much cheaper, which inlining allows and materializing doesn't.

so the rules, as the postgres 12 release notes put them: a CTE is inlined automatically if it's referenced once, isn't recursive and has no side effects. MATERIALIZED prevents that, NOT MATERIALIZED forces it for a CTE referenced more than once. (a CTE with side effects, like a DELETE ... RETURNING, is always run exactly once.)

keylines

  • WITH name AS (query) names a subquery for one statement. later CTEs can use earlier ones.
  • use a CTE for readability: one named step at a time, top to bottom.
  • used once, it's inlined: planned as if the subquery were written in place.
  • used twice, it's materialized: computed once, its result scanned each time.
  • MATERIALIZED and NOT MATERIALIZED override the default. recursive CTEs are part 4.