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.
writing one
the CTE version, for real:
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;| nametext | citytext | nint8 |
|---|---|---|
| Maya Chen | San Francisco | 57 |
| Mei Kowalski | Hamburg | 36 |
| Grace Okafor | Lagos | 33 |
| Zoe Martin | Lyon | 31 |
| Zoë Martin | Paris | 30 |
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:
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;| nametext | citytext | nint8 |
|---|---|---|
| Maya Chen | San Francisco | 57 |
| Mei Kowalski | Hamburg | 36 |
| Grace Okafor | Lagos | 33 |
| Zoe Martin | Lyon | 31 |
| Zoë Martin | Paris | 30 |
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:
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;| countrychar | regularsint8 |
|---|---|
| DE | 3 |
| FR | 2 |
| IE | 2 |
| PT | 2 |
| BR | 1 |
| CA | 1 |
| GB | 1 |
| NG | 1 |
| US | 1 |
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:
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:
the same thing, as EXPLAIN prints it:
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;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:
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.
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);and the answer itself:
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);| above_averageint8 | average_ordersnumeric |
|---|---|
| 681 | 5.10 |
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.