Lesson 7 of 13 · 14m
CTEs and the Optimization Fence
Postgres 12+ inlines single-use CTEs, but MATERIALIZED still computes a shared intermediate once — and WITH RECURSIVE replaces N+1 hierarchy walks.
WITH recent AS (SELECT * FROM orders WHERE created_at > now() - interval '7 days') SELECT * FROM recent WHERE status = 'pending' — the CTE gives a subquery a name, which is the entire reason it exists: readable decomposition of a query that would otherwise be a nested mess. What it does to your plan depends entirely on which Postgres you're running, and that's the detail that bites people.
The wrong model, in both directions
Two wrong models survive on opposite ends. On Postgres 11 and older: "the CTE is just syntax sugar." False — those versions always materialized a CTE: computed once, stored to a temp structure, scanned by the outer query. The materialization was an optimization fence: predicates from the outer query could not be pushed inside. WHERE status = 'pending' outside could not reach orders inside; the whole 7-day slice materialized first, then got filtered. People learned this the hard way — "my CTE version is 50x slower than the subquery version" — and filed it under "CTEs are slow."
On Postgres 12 and newer, the model flipped: released October 2019, PG12's headline change was that single-use, non-recursive CTEs get inlined — folded into the outer query exactly like a subquery, predicates pushed down, fence gone. The wrong model now is the old reflex: "never use CTEs in hot paths." That's obsolete advice from a dead version.
What the planner does today
Postgres 12+ inlines a CTE when it's referenced once, isn't RECURSIVE, has no side effects, and isn't marked MATERIALIZED. Reference it twice — FROM recent r1 JOIN recent r2 — and it materializes: computed once, read twice, which is usually what you wanted anyway. You can force either side with explicit syntax: WITH x AS MATERIALIZED (...) keeps the fence (sometimes a deliberate tool — computing a small fixed set once so the planner sizes it correctly), and AS NOT MATERIALIZED forces inlining even for multi-referenced CTEs.
The fence isn't pure villainy. A MATERIALIZED CTE is the sanctioned way to compute an expensive shared intermediate once — say, a deduplicated user set joined by three different aggregations — instead of letting the planner inline it into each branch and compute it three times. The failure mode is using it reflexively; the success mode is measuring first.
The recursive member of the family
WITH RECURSIVE is a different machine: it iterates. The non-recursive term seeds a working table; the recursive term consumes it and feeds results back until the term returns empty.
WITH RECURSIVE subordinates AS (
SELECT id, manager_id, name FROM employees WHERE id = 81
UNION ALL
SELECT e.id, e.manager_id, e.name FROM employees e
JOIN subordinates s ON e.manager_id = s.id
) SELECT * FROM subordinates;Org charts, category trees, permission inheritance, graph reachability — anything hierarchical that people otherwise fetch with N+1 queries. Two traps: no cycle protection (a manager_id loop iterates forever — add a WHERE against a path array or a depth limit), and the UNION vs UNION ALL distinction matters because UNION's dedup pass on every iteration isn't free.
CTE versus temp table versus subquery
A subquery inlined by the planner, a CTE inlined by the planner — same plan, pick whichever reads better. A multi-use CTE materialized once — cheaper than three subqueries each recomputing. A temp table — persists for the session, gets its own statistics via ANALYZE, can hold indexes. For pipeline work that stage-loads data across several statements, a real CREATE TEMP TABLE plus ANALYZE beats a clever multi-CTE query because the planner gets honest stats on it — CTEs keep no statistics of their own.
What to actually do
- On PG12+, write CTEs for readability. The planner inlines single-use ones; you get the clarity without the fence.
- Know which PG you're on before applying anyone's "CTEs are slow/fast" advice — the rule inverted in October 2019.
- Use
AS MATERIALIZEDdeliberately and rarely: a genuinely shared expensive intermediate measured to beat inlining. - For hierarchies,
WITH RECURSIVEbeats the N+1 loop; protect against cycles with a depth counter or path-array check. - Multi-statement ETL stages:
CREATE TEMP TABLE+ANALYZE, not a 200-line CTE chain — the planner needs statistics it can't get from a materialized CTE.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
PostgreSQL Fixed 52 CVEs in One Release. The Upgrade Is the Easy Part.
PostgreSQL 18.7, 17.12, 16.16, 15.20 and 14.25 fix 52 security vulnerabilities, almost twice August's record of 28. The binary swap took under a second in my test. The post-update steps are where the work is, and one of them makes some indexes several times bigger.
What PostgreSQL 15 Changed
A new version of the popular open-source database PostgreSQL is now available, offering performance improvements over PostgreSQL 14 and new functions and capabilities for managing workloads in local and distributed deployments. Released on October 13 by the PostgreSQL Global Development Group,…
PHP API Performance: N+1 Queries, cURL, and Connection Pools
A PHP API case study: fixing an N+1 query, twenty serial cURL calls, missing connection pooling, and stats recalculated on every request with Redis caching.