Part 18 / Topic 5 of 7
CTE materialization
Since PostgreSQL 12, a CTE referenced once is inlined — flattened into the main query so WHERE clauses and indexes reach inside it. Watch the outer filter dive into the CTE and use the index:
EXPLAIN (COSTS OFF)
WITH recent AS (
SELECT * FROM big_orders WHERE order_date > DATE '2024-06-01'
)
SELECT * FROM recent WHERE customer_id = 42;
QUERY PLAN
----------------------------------------------------
Bitmap Heap Scan on big_orders
Recheck Cond: (customer_id = 42)
Filter: (order_date > '2024-06-01'::date)
-> Bitmap Index Scan on idx_big_orders_customer
Index Cond: (customer_id = 42)
(5 rows)
One scan, both conditions merged — the CTE was a readability device, costing nothing. The exceptions, both spelled explicitly:
AS MATERIALIZEDforces the old behaviour: compute the CTE once into a buffer. You want this when the CTE is referenced several times and is expensive, or as an optimization fence when inlining produces a worse plan.AS NOT MATERIALIZEDforces inlining where Postgres would otherwise materialize (multiple references).
EXPLAIN (COSTS OFF)
WITH recent AS MATERIALIZED (
SELECT * FROM big_orders WHERE order_date > DATE '2024-06-01'
)
SELECT * FROM recent WHERE customer_id = 42;
QUERY PLAN
-----------------------------------------------------
CTE Scan on recent
Filter: (customer_id = 42)
CTE recent
-> Seq Scan on big_orders
Filter: (order_date > '2024-06-01'::date)
(5 rows)
Now the shape shows the fence: the CTE scans on its own, and customer_id = 42 filters the buffered result — the index unreachable behind the wall. The takeaway is calibration, not fear: write CTEs freely for structure (they're free), and reach for MATERIALIZED deliberately — as a cache for reuse or a fence against a misbehaving planner, never as a habit.
🧪 Quick quiz — answer from memory, then check.
- What happens to a single-reference CTE since PostgreSQL 12?
- When do you write AS MATERIALIZED on purpose?
Show the answers
- It's inlined into the main query — filters and indexes reach inside.
- Expensive CTE used multiple times (compute once), or as a deliberate optimization fence.
Done here? The practice set for Part 18 — 5 exercises with solutions — is on the part page.