Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

Since PostgreSQL 12, how are CTEs (WITH queries) planned, and when would you add MATERIALIZED or NOT MATERIALIZED?

Before PostgreSQL 12, every CTE was computed on its own and stored, so it acted as an optimization fence that filters from the outer query could not cross. Since version 12, a CTE that is not recursive, has no side effects and is referenced only once is inlined into the main query, so the planner can push predicates into it and use indexes. We add MATERIALIZED to force the old compute-once behaviour, and NOT MATERIALIZED to force inlining even when the CTE is referenced more than once.

Why this question is asked

CTEs, the WITH queries that let us name a sub-result and use it below, are one of the most common ways to make long SQL readable. The way PostgreSQL plans them changed in version 12, and that change sped up many queries and quietly altered the plans of others after upgrades. Interviewers ask about it because it tests whether we understand that readable SQL is not always the SQL the planner sees. In this answer, we will recap what a CTE is, see the old fence behaviour, follow how PostgreSQL 12 and later decide between inlining and materializing, and then look at when each keyword earns its place.

1A Quick Recap of CTEs and Materialization

A common table expression, or CTE, is a named query written in a WITH clause before the main statement. The main query can then read from that name as if it were a table. It is mainly a tool for readability: we can build a complex query in steps that each have a meaningful name.

There are two ways a database can execute a CTE. It can materialize it, which means it runs the CTE query once, keeps the rows in memory (spilling to a temporary file if they are large), and lets the main query scan that stored result. Or it can inline it, which means it pastes the CTE's query into the main query as a subquery, as if we had never named it, and plans the whole thing together. Inlining lets the planner move a filter from the outer query into the inner one, which is called predicate push-down.

2The Old Behaviour: An Optimization Fence

Up to PostgreSQL 11, every CTE was materialized, always. The planner treated it as a separate, sealed query. That is what people meant by an optimization fence: nothing from outside could pass through it. Look at this query against a large orders table with an index on customer_id.

Java
WITH recent AS (
SELECT * FROM orders
WHERE created_at > now() - interval '7 days'
)
SELECT * FROM recent WHERE customer_id = 42;
-- PostgreSQL 11 plan:
-- CTE Scan on recent (Filter: customer_id = 42)
-- CTE recent
-- -> Seq Scan on orders (Filter: created_at > ...) -- reads a week of orders, say 3 million rows
-- PostgreSQL 12 and later:
-- Index Scan using orders_customer_id_idx on orders
-- Index Cond: customer_id = 42
-- Filter: created_at > ... -- reads only customer 42's rows

Notice what changed. In version 11 the database built the full list of last week's orders and then threw away everything except customer 42. In version 12 the CTE is folded into the main query, the planner sees both conditions together, and it uses the customer_id index. The query text is identical; only the planning rule changed.

The fence was not always a bug. Many teams used CTEs on purpose to stop the planner from doing something they did not want, which is exactly why some queries got slower after an upgrade to 12.

3How PostgreSQL 12 and Later Decide

The rule since version 12 is simple to state. A CTE is inlined automatically when three things are true: it is not recursive, it is side-effect-free, and the main query references it exactly once. Side-effect-free means it is a plain SELECT with no volatile functions such as random() or nextval(); a stable function like now() is fine. If the CTE is referenced two or more times, PostgreSQL still materializes it by default, because computing it once and reading it twice is usually cheaper than computing it twice.

Two kinds of CTE are always materialized, whatever we write. A recursive CTE (WITH RECURSIVE) is evaluated with a working table that grows step by step, so it cannot be pasted into the outer query. A data-modifying CTE, one that contains INSERT, UPDATE or DELETE, is executed exactly once and to completion even if nothing reads its result, because its side effects must happen exactly once.

Step throughHow PostgreSQL 12+ plans a CTE
  1. Recursive or data-modifying?
    YesAlways materializedNoNext check
  2. Contains a volatile function?
    YesMaterializedNoNext check
  3. Written AS MATERIALIZED?
    YesMaterialized, computed onceNoNext check
  4. Written AS NOT MATERIALIZED?
    YesInlined at every referenceNoNext check
  5. Referenced exactly once?
    YesInlined, predicates pushed downNoMaterialized, computed once

5 steps in order. Play them, or step through them one at a time.

The keywords only change the outcome for plain SELECT CTEs; recursive and data-modifying ones are always materialized.

So the keywords only matter for the cases in between, and the flow below shows the order in which the decision is taken.

4When to Write MATERIALIZED

We force materialization in two situations. The first is an expensive CTE that is referenced several times. That is already the default, but writing MATERIALIZED makes the intent explicit and protects it from a later edit that drops one reference. The second, more interesting one is a CTE referenced once where push-down produces a worse plan. A typical case is a CTE that narrows a big table to a few hundred rows with a selective condition, followed by a join the planner misestimates once everything is planned together.

SQL
WITH hot AS MATERIALIZED (
SELECT id FROM products
WHERE tags @> ARRAY['clearance'] -- about 300 rows, GIN index
)
SELECT p.*, s.qty
FROM hot h
JOIN products p ON p.id = h.id
JOIN stock s ON s.product_id = h.id; -- the small set drives the joins

Notice the trade-off. A materialized CTE has no indexes and only rough statistics, so if it turns out to hold millions of rows, joins against it can be slow. We use MATERIALIZED as a deliberate fence after looking at EXPLAIN ANALYZE, not as a habit. After upgrading old code from version 11, adding MATERIALIZED to the few queries that relied on the fence restores the old plans while we study them.

5When to Write NOT MATERIALIZED

NOT MATERIALIZED does the opposite: it asks PostgreSQL to inline the CTE even though it is referenced more than once. That pays off when each reference applies a selective filter that an index can serve, so running the inlined query twice through an index is far cheaper than computing the whole CTE once.

SQL
WITH v AS NOT MATERIALIZED (
SELECT * FROM order_summary_view -- a wide view over millions of rows
)
SELECT * FROM v WHERE order_id = 1001
UNION ALL
SELECT * FROM v WHERE order_id = 2002; -- each branch becomes an index lookup

Without the keyword, PostgreSQL would build the whole view once and scan it twice. With it, each branch uses the index on order_id. The cost we accept is that the CTE's work is repeated at every reference, which is bad when the CTE is expensive and the filters are not selective. The keyword is ignored for recursive and data-modifying CTEs, which stay materialized.

6Follow-up questions

What did upgrading to PostgreSQL 12 do to existing queries?

Every single-reference, side-effect-free CTE silently became inlinable. Most queries got faster because filters could now reach indexes, but queries that relied on the fence could get a different and sometimes worse plan. A safe upgrade compares the plans of the top queries and adds MATERIALIZED where the old plan was the better one.

Is a CTE ever faster than the same query written with a subquery?

Since version 12, an inlined CTE and the equivalent subquery produce the same plan, so neither is faster. A materialized CTE can be faster when it is referenced many times or when it stops a bad push-down, and slower when it hides an index that a filter could have used.

How do I see whether a CTE was inlined?

Run EXPLAIN. A materialized CTE appears as a CTE node with a CTE Scan reading from it. An inlined CTE leaves no trace in the plan: we only see the underlying table scans and joins, with the outer filters applied directly to them.

7Conclusion

In this answer, we saw that PostgreSQL used to materialize every CTE, which made it an optimization fence. Since version 12, a non-recursive, side-effect-free CTE referenced once is inlined so filters can be pushed down into it, while CTEs referenced several times are still materialized by default. MATERIALIZED forces the compute-once fence when it helps, NOT MATERIALIZED forces inlining across several references, and recursive and data-modifying CTEs are always materialized whatever we write.

What to say in the interviewAbout 90 seconds aloud

Open with

Up to PostgreSQL 11 every CTE was materialized: it ran once, its rows were stored, and the outer query scanned that result, so filters from outside could not reach the tables inside.

Then, if they want more

People called it an optimization fence. Since version 12 the planner inlines a CTE when it is not recursive, has no side effects, meaning no data modification and no volatile functions, and is referenced exactly once. Then it behaves like a subquery, so a WHERE customer_id = 42 outside can be pushed in and use an index.

If the CTE is referenced more than once, the default is still to materialize it. I add MATERIALIZED when I want the fence on purpose, for example when the CTE is expensive and reused, or when inlining leads the planner into a bad join order, and I check it with EXPLAIN ANALYZE, because a materialized result has no indexes.

I add NOT MATERIALIZED when a CTE is referenced twice but each reference has a selective filter an index can serve, so repeating the work is cheaper than building the whole result. Recursive and data-modifying CTEs are always materialized regardless of the keyword.

When I upgrade from an older version, I compare plans for queries that used CTEs as a fence, and add MATERIALIZED where the old plan was better.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 12, PostgreSQL 11
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Since PostgreSQL 12, how are CTEs (WITH queries) planned, and when would you add...": https://scrivio-interview-library.netlify.app/databases/query-optimization/b41c4d0b1a/