CTE Materialization & the Optimization Fence
the WITH clause that became a wall
Databasesdatabases / query performance
Friday refactor
One 80-line report query, three nested subqueries, unreadable. You lift the inner one into a CTE and reuse it:
WITH recent AS (
SELECT * FROM events
WHERE created_at > now() - interval '30 days'
)
SELECT r.user_id, r.kind, agg.n
FROM recent r
JOIN (SELECT user_id, count(*) n FROM recent GROUP BY 1) agg
ON agg.user_id = r.user_id
WHERE r.user_id = 4812;
Same rows, same indexes, prettier SQL. 18 ms → 740 ms.
What the plan tells you
-- before: subquery
Index Scan using events_user_created_idx on events
Index Cond: (user_id = 4812 AND created_at > ...)
rows=37
-- after: CTE
CTE Scan on recent (rows=2431900)
Filter: (user_id = 4812)
The user_id = 4812 predicate never reached the index. Postgres built all 2.4M recent rows into a tuplestore, then filtered them row by row.
The optimization fence
A CTE is handled one of two ways:
- inlined — spliced into the outer query, so the planner can push predicates down and choose indexes
- materialized — executed once, result parked in a temp tuplestore, outer query scans that
Materialized is a fence. No predicate crosses it, and the planner's row estimate for the CTE output is a guess.
Postgres ≤ 11 always materialized. Postgres 12+ inlines automatically — but only when all three hold:
- referenced exactly once
- not
RECURSIVE - side-effect free (no
VOLATILEfunction, noINSERT/UPDATE/DELETE)
Break any one and you are back behind the fence. That second reference to recent is what cost you 722 ms.
Taking the wheel
Postgres 12+ (and SQLite 3.35+) let you state it explicitly:
WITH recent AS NOT MATERIALIZED (...) -- force inline
WITH recent AS MATERIALIZED (...) -- force the fence
For the query above, NOT MATERIALIZED restores the index scan — at the price of evaluating the CTE twice. Often the better fix is to stop relying on the planner and push the filter inside:
WITH recent AS (
SELECT * FROM events
WHERE created_at > now() - interval '30 days'
AND user_id = 4812
)
The fence is sometimes the point
Do not reflexively sprinkle NOT MATERIALIZED. A CTE that scans 10M rows and aggregates down to 50, referenced 4 times, becomes 4 full scans when inlined. Materializing runs it once.
Three cases where you want the fence:
- expensive aggregate, referenced more than once
- a CTE with
LIMIT, where "which rows" must be decided once — inlining can change results with a volatileORDER BY random() - a data-modifying CTE (
INSERT ... RETURNING), which is always materialized anyway
Portability gotcha
MATERIALIZED is Postgres/SQLite spelling. MySQL 8 and SQL Server decide for themselves with no hint, and their defaults differ from Postgres. A CTE rewrite that fixed a query on Postgres can do nothing — or the opposite — after a migration. Always re-read the plan on the engine you ship.
Your exercise
Take any query in your codebase with a WITH clause. Run EXPLAIN (ANALYZE, BUFFERS) and look for a CTE Scan node. If you find one:
- count how many times that CTE name appears in the query
- if it is once, ask why it still materialized — volatile function?
RECURSIVE? - if it is twice or more, try
AS NOT MATERIALIZEDand compare total time andshared readblocks
Which won, and by how much?