Sub topic 9
How engines execute CTEs: materialized or inlined
A CTE is a way to write a query. It does not tell the database how to run it. This chapter explains the two strategies engines use, what each one costs, and how to control the choice where your database allows it.
This chapter assumes you can write non-recursive and recursive CTEs, read basic EXPLAIN output, and know what an index is. The examples use PostgreSQL 12 or later unless a section says otherwise.
Two ways to run the same text
When the planner meets a CTE, it can do one of two things.
- Inline it. The planner treats the CTE like a view or a derived table. It substitutes the CTE's query into each place that references it and optimizes the whole statement as one unit.
- Materialize it. The engine runs the CTE's query once, stores the rows in a temporary buffer (in memory, spilling to disk if large), and lets the outer query read from that buffer.
Both strategies must return the same rows. They differ in speed, memory use, and a few side effects.
| Strategy | Strength | Cost |
|---|---|---|
| Inlined | Filters and joins from the outer query can move into the CTE, so indexes can be used | If the CTE is referenced twice, its query may run twice |
| Materialized | The CTE's query runs once, and every reference sees the same rows | The stored result has no indexes or statistics, and outer filters cannot reach inside |
The optimization fence
A materialized CTE acts as an optimization fence: the planner optimizes the CTE's query separately from the outer query. Predicates in the outer query cannot be pushed into it, and join order cannot be rearranged across the boundary.
Here is a setup in PostgreSQL that makes the effect visible.
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL,
order_date date NOT NULL,
amount numeric(10,2) NOT NULL
);
INSERT INTO orders
SELECT g, g % 1000, DATE '2025-01-01' + (g % 700), (g % 90) + 10
FROM generate_series(1, 200000) AS g;
CREATE INDEX orders_customer_idx ON orders (customer_id);
ANALYZE orders;Now ask for one customer's total through a CTE, and force materialization.
EXPLAIN
WITH totals AS MATERIALIZED (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT total FROM totals WHERE customer_id = 42;The plan aggregates all 200,000 rows into 1,000 groups, stores them, and then a CTE Scan on totals applies customer_id = 42 as a filter. The work for the other 999 customers is wasted.
Change MATERIALIZED to NOT MATERIALIZED and run EXPLAIN again. There is no CTE Scan node. The planner pushes customer_id = 42 down through the GROUP BY, because customer_id is a grouping column. It can then use orders_customer_idx to read only that customer's rows.
EXPLAIN
WITH totals AS NOT MATERIALIZED (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT total FROM totals WHERE customer_id = 42;Exact costs and node names depend on your version and settings. The thing to look for is whether a CTE Scan node appears.
What PostgreSQL does by default
The history matters because you will meet code written for both behaviors.
- PostgreSQL 11 and earlier: every CTE was materialized. Developers used
WITHon purpose as a fence, and sometimes by accident. - PostgreSQL 12 and later: the planner inlines a CTE automatically when all of these are true:
- the CTE is not recursive,
- it has no side effects (it is not a data-modifying statement),
- it contains no volatile functions, and
- it is referenced exactly once.
Otherwise it is materialized.
You can override the default per CTE with MATERIALIZED or NOT MATERIALIZED.
WITH recent AS MATERIALIZED (
SELECT * FROM orders WHERE order_date >= DATE '2026-01-01'
)
SELECT COUNT(*) FROM recent;In this example the hint changes little, because the outer query adds no filter of its own. It matters when the CTE is large and the outer query is selective, or when the CTE is expensive and referenced several times.
Recursive and data-modifying CTEs are always materialized. A hint cannot change that.
When materialization helps
Materialization is not just a limitation. Four situations favor it.
- An expensive CTE referenced several times. If the CTE joins large tables and three parts of the query read it, computing it once is much cheaper than three times.
- A deliberate fence. Sometimes the planner chooses a bad plan for a complex query, for example because it misestimates how many rows a subquery returns. Materializing the intermediate result gives the planner a fixed starting point.
- Consistent results from volatile functions. If a CTE calls
random(),clock_timestamp(), or a function with side effects, every reference should see the same rows. Materialization guarantees that. - Controlling side effects. A data-modifying CTE must run exactly once, to completion, whether or not the outer query reads its output.
Here is the volatile case. The CTE is referenced twice and contains random(), so PostgreSQL materializes it.
WITH pick AS (
SELECT random() AS x
)
SELECT a.x = b.x AS same_value
FROM pick a
CROSS JOIN pick b;The result is true. If the engine had inlined pick into both references, each reference would call random() separately and the comparison would almost always be false. Do not rely on identical behavior in other databases. Check how yours treats nondeterministic functions inside CTEs.
When inlining helps
Inlining wins when the outer query is more selective than the CTE.
- Filter pushdown. The
customer_id = 42example above is the classic case. - Join reordering. The planner can start from a small table in the outer query and probe the CTE's base tables by index.
- Avoiding a temporary buffer. A CTE that returns millions of rows has to be stored before the outer query reads it. Inlined, the rows can stream through.
A CTE that you reference once purely for readability should almost always be inlined. That is the PostgreSQL default, so you usually need no hint.
Reading the plan
In PostgreSQL, the plan tells you which strategy ran.
CTE Scan on namemeans the CTE was materialized and the outer query is reading the stored result.InitPlanorSubPlannodes can also appear for materialized CTEs, depending on how they are used.- No
CTE Scanand no mention of the CTE name means the CTE was inlined. Its tables appear directly in the plan.
With EXPLAIN ANALYZE, a CTE Scan shows the rows read from the buffer. Compare "rows" against "Rows Removed by Filter". A large number removed means the outer query is throwing away work the CTE did, and inlining may help.
A materialized CTE has no statistics of its own. The planner guesses its row count from the CTE's query plan, and the outer query's joins and filters are estimated against that guess. When the guess is wrong, the join strategy chosen above the CTE can also be wrong. This is a common source of slow queries that "look fine".
Other engines
The syntax of WITH is standard, but execution is not. Treat the following as a summary of documented behavior at the time of writing and check your version's documentation.
| Engine | Default behavior | Control |
|---|---|---|
| PostgreSQL 12+ | Inline if referenced once and side-effect free, otherwise materialize | `MATERIALIZED`, `NOT MATERIALIZED` |
| PostgreSQL 11 and earlier | Always materialize | None (rewrite as a subquery to inline) |
| SQL Server | Inlined like a view. A CTE referenced twice can be evaluated twice | No keyword. Use a temporary table to force a single evaluation |
| MySQL 8.0 and MariaDB | Treated like a derived table. Merged into the outer query when possible, otherwise materialized | Optimizer switches such as `derived_merge`, and optimizer hints |
| Oracle | Optimizer decides. Often materializes a CTE referenced more than once | `/*+ MATERIALIZE */`, `/*+ INLINE */` hints |
| SQLite 3.35+ | Subquery if used once, materialized if used more than once | `MATERIALIZED`, `NOT MATERIALIZED` |
Two consequences follow for portable code.
- A
MATERIALIZEDkeyword is a PostgreSQL and SQLite feature. SQL Server and MySQL will reject it as a syntax error. - In SQL Server, "I referenced the CTE twice so it ran once" is false. If a CTE is expensive and used twice there, put its result in a temporary table first.
Recursive and data-modifying CTEs
A recursive CTE is evaluated iteratively. The engine runs the anchor member and stores its rows in a working table. It then repeatedly runs the recursive member against the previous round's rows and appends the new rows, until a round produces nothing. Because of this evaluation model, the result is materialized in the sense that it is built up in a buffer.
Pushing outer filters into a recursive CTE is not generally safe. A filter on the outer query's depth column, for example, cannot be applied inside the recursion without changing which rows are reached. For that reason the optimizer leaves the recursion alone. If you only need the first few levels, put the limit inside the recursive member, as in WHERE depth < 3, rather than in the outer query.
A data-modifying CTE in PostgreSQL always runs to completion exactly once, even if the outer query never reads its RETURNING rows. This is what makes the archive pattern work.
WITH moved AS (
DELETE FROM orders
WHERE order_date < DATE '2020-01-01'
RETURNING *
)
INSERT INTO orders_archive
SELECT * FROM moved;All sub-statements in a WITH run against the same snapshot. They cannot see each other's changes to the target tables. The only way to pass data between them is RETURNING.
A decision procedure
When a query with a CTE is slow, work through these steps.
- Run
EXPLAIN (ANALYZE, BUFFERS)and check whether aCTE Scanappears. - If it appears and the outer query filters most of the rows away, test
NOT MATERIALIZED(or rewrite as a subquery on engines without the keyword). - If the CTE is absent from the plan, and the CTE is referenced several times and is expensive, test
MATERIALIZED. - If estimates for a joined materialized CTE are far off, consider a temporary table with an index and
ANALYZE. This gives the planner real statistics. - Compare timings on realistic data volumes. Small test tables often hide the difference.
Summary
- A CTE is a naming construct. The engine may inline it or materialize it.
- Materialization runs the CTE once and acts as an optimization fence. Inlining lets filters and joins reach the underlying tables.
- PostgreSQL 12 and later inline CTEs that are referenced once, non-recursive, and free of side effects and volatile functions. Hints override the default except for recursive and data-modifying CTEs.
- Other engines differ. SQL Server inlines, MySQL treats CTEs as derived tables, and Oracle uses hints.
- Always confirm the strategy in the execution plan before and after a change.
Exercise
In PostgreSQL 14, a CTE named big_join joins three large tables. The query references big_join three times and runs slowly. EXPLAIN shows no CTE Scan node, and the three tables are joined three separate times. What most likely happened, and how do you fix it?
Show answer
Something forced inlining. Without a hint, a CTE referenced three times would be materialized, so most likely the CTE was written with NOT MATERIALIZED. The engine then evaluated the join once per reference. Remove NOT MATERIALIZED, or write big_join AS MATERIALIZED (...), so the joins run once and all three references read the stored result. Re-run EXPLAIN (ANALYZE, BUFFERS) to confirm that a single CTE Scan source appears and the timing improves.
Exercise
You write WITH totals AS MATERIALIZED (SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id) SELECT total FROM totals WHERE customer_id = 42; and it is slower than expected on a table with an index on customer_id. Why, and what are two ways to change it?
Show answer
Materialization prevents the filter customer_id = 42 from being pushed into the CTE, so the engine aggregates every customer and then discards all but one row. Fix it by removing MATERIALIZED (or using NOT MATERIALIZED), which lets the planner push the filter through the GROUP BY and use the index. Alternatively, put WHERE customer_id = 42 inside the CTE's own query. The second approach works on any engine, including those without the hint keywords.
Exercise
A colleague moves a query from PostgreSQL to SQL Server. The query has WITH expensive AS MATERIALIZED (...) and references expensive twice. What two problems will they hit?
Show answer
First, SQL Server does not support the MATERIALIZED keyword, so the statement fails with a syntax error. Second, even after removing the keyword, SQL Server inlines CTEs, so the expensive query may be evaluated once per reference instead of once. To get single evaluation, they should insert the CTE's result into a temporary table (optionally indexing it) and query that table twice.