CTE Optimization Fences (MATERIALIZED vs NOT MATERIALIZED)
Control whether PostgreSQL materializes a CTE or inlines it into the plan.
In plain words
Either the database works out the CTE once and keeps the result, or it blends the CTE into the main query and plans everything together.
Think of it like…
Asking a colleague for "all orders this month" on a printout and then searching it for one customer (materialised), versus asking them directly for "this customer's orders this month" so they can use the filing index (inlined).
Where you’ve seen it
WITH recent AS (SELECT * FROM orders WHERE created_at > now() - interval '30 days') SELECT * FROM recent WHERE customer_id = 42; On PostgreSQL 11 the CTE was always materialised, so it read every recent order (4 million rows) before filtering. On 12+ it's inlined and uses the index on orders (customer_id, created_at), returning in under a millisecond.
Words you’ll hear
- Inlining
- Merging the CTE into the outer query so it's planned as one query.
- Materialisation
- Computing the CTE once into a temporary result the outer query scans.
- Optimisation fence
- A boundary outer filters and join conditions can't be pushed through.
- CTE Scan
- The EXPLAIN node that shows a materialised CTE is being read.
Visual diagram
Theory & example queries
PostgreSQL's rules
Since PostgreSQL 12, a CTE is inlined automatically when it's non-recursive, has no side effects (no INSERT, UPDATE or DELETE, no volatile functions like random() or nextval()), and is referenced exactly once. Otherwise it's materialised: computed once, stored in memory (spilling to disk if large), and read through a CTE Scan node. Before 12, every CTE was materialised, which is where the "CTEs are an optimisation fence" reputation comes from.
You can override the default. AS MATERIALIZED forces a single computation, useful when an expensive CTE is referenced several times, or when you deliberately want to stop the planner from merging it, for example to force an expensive function to run once per row of a small set. AS NOT MATERIALIZED forces inlining even for a CTE referenced twice, so each reference can use indexes and pushed-down filters, at the cost of computing it twice.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
WITH o AS NOT MATERIALIZED ( SELECT * FROM orders )SELECT ( SELECT COUNT(*) FROM o WHERE customer_id = 42 ) AS orders_42, ( SELECT COUNT(*) FROM o WHERE customer_id = 43 ) AS orders_43;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected output1 sample row
| orders_42 | orders_43 |
|---|---|
| 18 | 7 |
Note: Illustrative counts; NOT MATERIALIZED allows the optimizer to inline the CTE, and actual plan choice remains engine- and statistics-dependent.
Each reference becomes an index lookup instead of both scanning a full copy of orders.
Key takeaway: Once-referenced, side-effect-free CTEs are inlined; override with (NOT) MATERIALIZED.
Reading plans and other databases
In EXPLAIN, a materialised CTE appears as a separate CTE recent subplan and a CTE Scan on recent node, often with a Filter above it removing most rows. An inlined CTE leaves no trace; you just see ordinary scans and joins. If a CTE Scan reads far more rows than the query returns, try NOT MATERIALIZED and compare with EXPLAIN ANALYZE.
Other engines differ. SQL Server always inlines CTEs and re-evaluates them for each reference; to compute once, use a temporary table. MySQL 8 chooses between merging and materialising derived tables and CTEs, with optimizer hints MERGE and NO_MERGE. Oracle decides automatically and accepts the MATERIALIZE and INLINE hints. In all of them, a temp table with an index is the explicit option when an intermediate result is large and reused.
CTE Scan on recent (rows=4,012,331) → Filter: (customer_id = 42), Rows Removed by Filter: 4,012,318 The filter runs after the whole CTE was built; NOT MATERIALIZED would let it use the index.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Check the version and references
On PostgreSQL 12+, count how often each CTE is referenced and whether it has side effects or volatile functions.
referenced once, no side effects → inlined
When to use it & trade-offs
What it is
A CTE can be executed two ways. Inlined, it's merged into the main query like a subquery, so the planner can push filters into it and use indexes. Materialised, it's computed once into a temporary result, and the main query reads that result, which is called an optimisation fence because outer filters can't reach inside. PostgreSQL lets you choose with WITH x AS MATERIALIZED (…) or AS NOT MATERIALIZED (…).
Why it matters: The same CTE can be milliseconds or minutes depending on which way it runs. Upgrades from PostgreSQL 11 to 12 changed the default and sped up some queries while slowing others, and people still use MATERIALIZED as a deliberate planner hint. Knowing the rules explains surprising plans, and senior PostgreSQL interviews ask about it.
When to reach for it
- MATERIALIZED for costly CTEs used more than once
- NOT MATERIALIZED when a fence blocks an index
- Explaining plan changes after a PostgreSQL upgrade
When to avoid or be careful
- Assuming CTEs are always fences on modern PostgreSQL
- Adding hints without measuring with EXPLAIN ANALYZE
- Relying on CTEs to compute once in SQL Server
MATERIALIZED vs NOT MATERIALIZED vs a temp table
Strengths: Computed once; predictable evaluation.
Watch out: No index use or filter pushdown into the result.
Strengths: Planner can push filters in and use indexes.
Watch out: Computed once per reference.
Strengths: Can be indexed and analysed; works in every database.
Watch out: Extra statements; must be created and dropped.
Interview signals & numbers to know
When this topic comes up
- “This query got faster/slower after upgrading to PostgreSQL 12”
- “Why isn't my index used inside the CTE?”
- CTE Scan in EXPLAIN
- Optimisation fences
- Planner hints
Benchmarks & rules of thumb
- PostgreSQL 12
- automatic CTE inlining introduced
- 1
- reference count for automatic inlining
- 2+
- references → materialised by default
Common mistakes & follow-ups
Common interview mistakes
- Expecting NOT MATERIALIZED to inline a CTE that calls random() or modifies data; PostgreSQL ignores the hint for CTEs that aren't side-effect-free.
- Assuming a CTE referenced in two places is computed once in SQL Server.
- Rewriting CTEs into subqueries for speed on PostgreSQL 12+, where the plan is usually identical.
Likely interviewer follow-ups
- What's an optimisation fence, and does PostgreSQL still have one?
- When would you add MATERIALIZED to a CTE?
- How does SQL Server treat a CTE referenced twice?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply CTE Optimization Fences (MATERIALIZED vs NOT MATERIALIZED) with hands-on SQL practice and interview Q&A.