Skip to content

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 MATERIALIZED deliberately and rarely: a genuinely shared expensive intermediate measured to beat inlining.
  • For hierarchies, WITH RECURSIVE beats 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?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.