The symptom
A common table expression (a WITH query) can be executed in two ways. The engine can fold it into the outer query, as if you had written a subquery, so that outer filters reach the tables and their indexes. Or it can run the CTE once, keep the whole result, and read from that copy. The second way is materialization. It is right when the result is needed several times in full. It is wasteful when the outer query wants a few rows, because the filter is applied to the stored result after all the work has been done.
das query plan viewer flags PostgreSQL plans where a CTE Scan throws away most of what the CTE produced. The examples use a shop schema with 400,000 orders and an index on orders (customer_id).
Diagnose it
A CTE referenced once is folded in
PostgreSQL inlines a plain SELECT CTE that the query refers to once. The filter on customer_id goes straight to the index and there is no CTE Scan in the plan:
CREATE INDEX orders_customer_idx ON orders (customer_id);
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
WITH customer_totals AS (
SELECT customer_id, count(*) AS orders, sum(total) AS spent
FROM orders
GROUP BY customer_id
)
SELECT * FROM customer_totals WHERE customer_id = 4242;
GroupAggregate (cost=4.59..84.65 rows=1 width=44) (actual rows=1.00 loops=1)
-> Bitmap Heap Scan on orders (cost=4.59..84.54 rows=21 width=10) (actual rows=20.00 loops=1)
Recheck Cond: (customer_id = 4242)
Heap Blocks: exact=20
-> Bitmap Index Scan on orders_customer_idx (cost=0.00..4.58 rows=21 width=0) (actual rows=20.00 loops=1)
Index Cond: (customer_id = 4242)
Index Searches: 1
A CTE referenced twice is materialized
Refer to the same CTE a second time and PostgreSQL computes it once and stores it:
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
WITH customer_totals AS (
SELECT customer_id, count(*) AS orders, sum(total) AS spent
FROM orders
GROUP BY customer_id
)
SELECT a.spent AS spent_4242, b.spent AS spent_4243
FROM customer_totals AS a
CROSS JOIN customer_totals AS b
WHERE a.customer_id = 4242 AND b.customer_id = 4243;
Nested Loop (cost=11700.51..12487.17 rows=1 width=64) (actual rows=1.00 loops=1)
CTE customer_totals
-> HashAggregate (cost=11482.00..11700.51 rows=17481 width=44) (actual rows=18001.00 loops=1)
Group Key: orders.customer_id
Batches: 1 Memory Usage: 7185kB
-> Seq Scan on orders (cost=0.00..8482.00 rows=400000 width=10) (actual rows=400000.00 loops=1)
-> CTE Scan on customer_totals a (cost=0.00..393.32 rows=1 width=32) (actual rows=1.00 loops=1)
Filter: (customer_id = 4242)
Rows Removed by Filter: 18000
Storage: Memory Maximum Storage: 1100kB
-> CTE Scan on customer_totals b (cost=0.00..393.32 rows=1 width=32) (actual rows=1.00 loops=1)
Filter: (customer_id = 4243)
Rows Removed by Filter: 18000
Storage: Memory Maximum Storage: 1100kB
The signs are the CTE customer_totals block, which reads all 400,000 orders and builds a row for every customer, and the CTE Scan nodes with a Filter and a large Rows Removed by Filter. Two customers were asked for and the totals of all of them were computed.
The keyword MATERIALIZED forces the same behavior for a CTE that is referenced once, so check for it in the query text when a plan has an unexpected CTE Scan.
MySQL: Materialize CTE
MySQL also materializes a CTE that is used more than once and says so in the tree format:
CREATE INDEX orders_customer_idx ON orders (customer_id);
EXPLAIN FORMAT=TREE
WITH customer_totals AS (
SELECT customer_id, count(*) AS orders, sum(total) AS spent
FROM orders
GROUP BY customer_id
)
SELECT a.spent AS spent_4242, b.spent AS spent_4243
FROM customer_totals AS a
CROSS JOIN customer_totals AS b
WHERE a.customer_id = 4242 AND b.customer_id = 4243;
-> Nested loop inner join (cost=32.8e+6 rows=327e+6)
-> Index lookup on a using <auto_key0> (customer_id=4242) (cost=81897..81900 rows=10)
-> Materialize CTE customer_totals if needed (cost=81896..81896 rows=18075)
-> Group aggregate: count(0), sum(orders.total) (cost=80089 rows=18075)
-> Index scan on orders using orders_customer_idx (cost=40225 rows=398641)
-> Index lookup on b using <auto_key0> (customer_id=4243) (cost=81897..81899 rows=10)
-> Materialize CTE customer_totals if needed (query plan printed elsewhere) (cost=81896..81896 rows=18075)
MySQL builds the temporary result once, adds an automatic key (<auto_key0>) and looks both customers up in it. The lookups are fast, but the whole of orders is still read and aggregated to build it.
Fix it
Add NOT MATERIALIZED
In PostgreSQL, NOT MATERIALIZED tells the planner to fold the CTE into each place it is used. Each reference then gets its own filter and its own index scan:
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
WITH customer_totals AS NOT MATERIALIZED (
SELECT customer_id, count(*) AS orders, sum(total) AS spent
FROM orders
GROUP BY customer_id
)
SELECT a.spent AS spent_4242, b.spent AS spent_4243
FROM customer_totals AS a
CROSS JOIN customer_totals AS b
WHERE a.customer_id = 4242 AND b.customer_id = 4243;
Nested Loop (cost=9.17..169.23 rows=1 width=64) (actual rows=1.00 loops=1)
-> GroupAggregate (cost=4.59..84.60 rows=1 width=44) (actual rows=1.00 loops=1)
-> Bitmap Heap Scan on orders (cost=4.59..84.54 rows=21 width=10) (actual rows=20.00 loops=1)
Recheck Cond: (customer_id = 4242)
Heap Blocks: exact=20
-> Bitmap Index Scan on orders_customer_idx (cost=0.00..4.58 rows=21 width=0) (actual rows=20.00 loops=1)
Index Cond: (customer_id = 4242)
Index Searches: 1
-> GroupAggregate (cost=4.59..84.60 rows=1 width=44) (actual rows=1.00 loops=1)
-> Bitmap Heap Scan on orders orders_1 (cost=4.59..84.54 rows=21 width=10) (actual rows=20.00 loops=1)
Recheck Cond: (customer_id = 4243)
Heap Blocks: exact=20
-> Bitmap Index Scan on orders_customer_idx (cost=0.00..4.58 rows=21 width=0) (actual rows=20.00 loops=1)
Index Cond: (customer_id = 4243)
Index Searches: 1
The CTE is now evaluated twice, once per reference, and each evaluation reads 20 rows instead of 400,000.
Move the filter into the CTE
When the CTE has to stay materialized, filter inside it so that less is computed and stored. This works in every engine:
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
WITH customer_totals AS (
SELECT customer_id, count(*) AS orders, sum(total) AS spent
FROM orders
WHERE customer_id IN (4242, 4243)
GROUP BY customer_id
)
SELECT a.spent AS spent_4242, b.spent AS spent_4243
FROM customer_totals AS a
CROSS JOIN customer_totals AS b
WHERE a.customer_id = 4242 AND b.customer_id = 4243;
Nested Loop (cost=163.94..165.79 rows=1 width=64) (actual rows=1.00 loops=1)
CTE customer_totals
-> GroupAggregate (cost=163.02..163.94 rows=41 width=44) (actual rows=2.00 loops=1)
Group Key: orders.customer_id
-> Sort (cost=163.02..163.12 rows=41 width=10) (actual rows=40.00 loops=1)
Sort Key: orders.customer_id
Sort Method: quicksort Memory: 26kB
-> Bitmap Heap Scan on orders (cost=9.17..161.92 rows=41 width=10) (actual rows=40.00 loops=1)
Recheck Cond: (customer_id = ANY ('{4242,4243}'::integer[]))
Heap Blocks: exact=40
-> Bitmap Index Scan on orders_customer_idx (cost=0.00..9.16 rows=41 width=0) (actual rows=40.00 loops=1)
Index Cond: (customer_id = ANY ('{4242,4243}'::integer[]))
Index Searches: 1
-> CTE Scan on customer_totals a (cost=0.00..0.92 rows=1 width=32) (actual rows=1.00 loops=1)
Filter: (customer_id = 4242)
Rows Removed by Filter: 1
Storage: Memory Maximum Storage: 17kB
-> CTE Scan on customer_totals b (cost=0.00..0.92 rows=1 width=32) (actual rows=1.00 loops=1)
Filter: (customer_id = 4243)
Rows Removed by Filter: 1
Storage: Memory Maximum Storage: 17kB
EXPLAIN FORMAT=TREE
WITH customer_totals AS (
SELECT customer_id, count(*) AS orders, sum(total) AS spent
FROM orders
WHERE customer_id IN (4242, 4243)
GROUP BY customer_id
)
SELECT a.spent AS spent_4242, b.spent AS spent_4243
FROM customer_totals AS a
CROSS JOIN customer_totals AS b
WHERE a.customer_id = 4242 AND b.customer_id = 4243;
-> Nested loop inner join (cost=192 rows=1600)
-> Index lookup on a using <auto_key0> (customer_id=4242) (cost=26.9..27.9 rows=4)
-> Materialize CTE customer_totals if needed (cost=26.5..26.5 rows=40)
-> Group aggregate: count(0), sum(orders.total) (cost=22.5 rows=40)
-> Index range scan on orders using orders_customer_idx over (customer_id = 4242) OR (customer_id = 4243), with index condition: (orders.customer_id in (4242,4243)) (cost=18.5 rows=40)
-> Index lookup on b using <auto_key0> (customer_id=4243) (cost=26.8..27.6 rows=4)
-> Materialize CTE customer_totals if needed (query plan printed elsewhere) (cost=26.5..26.5 rows=40)
When to leave it alone
Materialization is the better plan when the CTE is expensive, is used several times, and each use needs most of its rows: computing it once is cheaper than computing it for every reference. It is also a deliberate tool. Writing AS MATERIALIZED stops the planner from merging the CTE into a join order that its estimates get wrong, which is one of the fixes for a row goal that backfires. Leave a CTE Scan alone when it removes few rows.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- Look for CTE Scan nodes and the CTE block that feeds them.
- Compare the rows the CTE produced with the rows the CTE Scan kept.
- Count how many times the query refers to the CTE and check for the MATERIALIZED keyword.
- Try NOT MATERIALIZED and compare the plans.
- Or move the filter inside the CTE.
- Keep materialization when the full result is used more than once.
Questions that come up
What does CTE Scan mean in a PostgreSQL plan?
It reads from the stored result of a materialized CTE. The CTE itself appears as a separate block in the plan and is executed once. Any filter shown on the CTE Scan is applied to the stored result, after the CTE has been computed in full.
When does PostgreSQL materialize a CTE?
When the query refers to the CTE more than once, when it is marked MATERIALIZED, when it is recursive, or when it is not a plain SELECT without side effects. A simple SELECT CTE that is referenced once is folded into the outer query.
What does NOT MATERIALIZED do?
It asks PostgreSQL to fold the CTE into the outer query at every place it is referenced, so that filters and join conditions from the outer query can be used inside it. The CTE is then evaluated once per reference instead of once in total.
Are CTEs slower than subqueries?
Not when the engine folds them in: the plan is then the same as for a subquery. They are slower only when materialization computes more rows than the outer query needs. Check the plan for CTE Scan in PostgreSQL or Materialize CTE in MySQL.
Does SQL Server materialize CTEs?
No. SQL Server always expands a CTE into the query where it is used, so a CTE referenced twice is evaluated twice. To compute an intermediate result once in SQL Server, store it in a temporary table.