Sub topic 9
How Engines Execute CTEs: Materialized or Inlined
This chapter assumes you know SELECT, joins, aggregates, and basic CTE syntax. It focuses on execution behavior: what a database does with a CTE after it parses the query.
A common table expression, or CTE, is a named query introduced with WITH. The name makes a query easier to read, but it does not automatically mean that the database creates a temporary table. The database optimizer chooses how to execute it.
The logical view and the physical plan
Consider this query:
WITH recent_orders AS (
SELECT *
FROM orders
WHERE order_date >= DATE '2026-01-01'
)
SELECT COUNT(*)
FROM recent_orders;Logically, the database first defines recent_orders, then counts its rows. Physically, the optimizer might:
- Run the CTE query and store its rows temporarily.
- Substitute the CTE query into the outer query.
- Push the outer filter, join, or aggregate into the CTE query.
- Use different behavior depending on how many times the CTE is referenced.
These choices do not change the intended result. They can change memory use, disk use, CPU work, and response time.
Materialization: compute and store
Materialization means that the database evaluates a CTE and stores its result for later use. The stored result might exist in memory or in temporary files.
Materialization can help when a costly CTE is referenced more than once. The database can compute the result once and read it repeatedly.
WITH expensive_totals AS MATERIALIZED (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT
c.name,
t.total
FROM customers AS c
JOIN expensive_totals AS t
ON t.customer_id = c.id
WHERE t.total > 1000;In PostgreSQL 12 and later, MATERIALIZED requests this behavior for a non-recursive CTE. The query may use more temporary storage than an inlined version, especially if the outer query needs only a small part of the CTE result.
Materialization can also create an optimization boundary. For example, an outer WHERE condition may not be pushed into the materialized CTE. The engine must produce the requested intermediate result before applying the outer condition.
Inlining: substitute the CTE into the query
Inlining means that the optimizer treats the CTE much like a named subquery and combines it with the surrounding query. This can allow predicate pushdown, join reordering, and index use.
WITH recent_orders AS NOT MATERIALIZED (
SELECT *
FROM orders
WHERE order_date >= DATE '2026-01-01'
)
SELECT COUNT(*)
FROM recent_orders
WHERE customer_id = 42;With inlining, the engine may effectively plan this as one query that filters by both date and customer. It can avoid storing every recent order when an index or another access path makes the narrower search cheaper.
In PostgreSQL, NOT MATERIALIZED allows the optimizer to inline the CTE when possible. It does not guarantee a particular physical plan. The optimizer can still choose another legal strategy.
Choosing between the strategies
Use the execution plan rather than guessing. A query that benefits from materialization in one database, data size, or index configuration may benefit from inlining in another.
| Situation | Materialization may help | Inlining may help |
|---|---|---|
| CTE referenced several times | Avoids repeating expensive work | Allows each use to receive different filters |
| Outer query filters heavily | Usually computes extra rows first | Pushes filters into the CTE |
| CTE performs an expensive aggregate | Reuses one computed result | Lets the optimizer combine operations |
| CTE result is large | Can consume temporary storage | May avoid storing the result |
A repeated reference does not always make materialization faster. If each reference uses a different selective condition, inlining may let each branch read only the rows it needs. Conversely, inlining can repeat an expensive calculation.
Database and query differences
CTE rules differ across database systems and versions. Some systems historically materialized non-recursive CTEs by default. Others generally treated them as inlineable views. The keywords MATERIALIZED and NOT MATERIALIZED are not portable SQL syntax.
Recursive CTEs are different from ordinary CTEs. Their recursive member must repeatedly consume rows produced by earlier iterations, so the engine needs a working structure for the recursion. Do not assume that the materialization rules for an ordinary CTE apply to a recursive one.
Data-modifying CTEs and CTEs containing volatile functions also have special rules in some systems. A function that returns a different value on each call can produce different results if the optimizer changes when or how often it evaluates the expression.
A practical tuning workflow
When a CTE query is slow:
- Run the query with a representative amount of data.
- Inspect the execution plan with your database's plan command, such as PostgreSQL's
EXPLAIN (ANALYZE, BUFFERS). - Check whether the CTE is scanned more than once.
- Look for a large intermediate result or repeated expensive work.
- Compare an ordinary CTE with an explicit
MATERIALIZEDorNOT MATERIALIZEDversion, if your dialect supports those options. - Confirm that indexes, row counts, and join estimates are realistic.
Do not add MATERIALIZED simply because a query uses a CTE. Add it when the plan and measurements show that reusing a computed result is worth the storage and optimization boundary.
Exercise
Why might NOT MATERIALIZED be faster when an outer query selects only one customer's rows from a large CTE?
Show answer
Inlining can push the customer filter into the CTE query, allowing the database to read or compute only the needed rows instead of storing the entire intermediate result.