Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 69/ 160
04. Subqueries & Common Table Expressions (CTEs)

CTE Optimization Fences (MATERIALIZED vs NOT MATERIALIZED)

Control whether PostgreSQL materializes a CTE or inlines it into the plan.

AdvancedMATERIALIZED · NOT MATERIALIZED3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Inlining a CTE that's referenced twiceQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  o AS NOT MATERIALIZED (3    SELECT4      *5    FROM6      orders7  )8SELECT9  (10    SELECT11      COUNT(*)12    FROM13      o14    WHERE15      customer_id = 4216  ) AS orders_42,17  (18    SELECT19      COUNT(*)20    FROM21      o22    WHERE23      customer_id = 4324  ) AS orders_43;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/24
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output1 sample row
Expected output
orders_42orders_43
187

Note: Illustrative counts; NOT MATERIALIZED allows the optimizer to inline the CTE, and actual plan choice remains engine- and statistics-dependent.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Spotting a fence in EXPLAIN

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.

Key takeaway: CTE Scan + big Filter = fence; SQL Server inlines, use temp tables to compute once.
Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Context

Check the version and references

On PostgreSQL 12+, count how often each CTE is referenced and whether it has side effects or volatile functions.

Focus at this step

referenced once, no side effects → inlined

What to watch at this step
Before 12
always materialised
Tip: use ← → to move between steps

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

AS MATERIALIZED
Best for: Expensive CTEs referenced several times; deliberate fences

Strengths: Computed once; predictable evaluation.

Watch out: No index use or filter pushdown into the result.

AS NOT MATERIALIZED
Best for: Selective outer filters on indexed columns

Strengths: Planner can push filters in and use indexes.

Watch out: Computed once per reference.

Temporary table
Best for: Large intermediate results reused across statements

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?
Interview tip: State PostgreSQL 12's three conditions for inlining, then give one reason to force each mode. That's the precise, version-aware answer interviewers look for.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Refactoring Deeply Nested Subqueries into Readable CTEs
Next topic
Recursive CTEs Fundamentals (Anchor Member + Recursive Member)