Quick revision
The short answer
Before PostgreSQL 12, every CTE was an optimisation fence: it was computed in full and stored, and filters from the outer query could not be pushed into it, so the indexes inside could not be used. From PostgreSQL 12, a non-recursive, side-effect-free CTE referenced once is inlined and optimised like a subquery, which is why the upgrade restored the speed. A materialised CTE is still right when an expensive CTE is used several times, or when we deliberately want to fix the evaluation order; data-modifying CTEs always run once and fully.
What to remember
In this answer, we saw that PostgreSQL 11 treated every CTE as an optimisation fence, computing it in full and blocking outer filters from reaching indexes inside, which made the split report fifty times slower. PostgreSQL 12 inlines non-recursive, side-effect-free CTEs referenced once, so the upgrade restored the indexed plan. A CTE Scan node in EXPLAIN shows materialisation, and we still choose it on purpose for expensive CTEs used several times or to fix a bad evaluation order, while data-modifying CTEs are always executed once and fully.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Before PostgreSQL 12, every CTE was an optimisation fence: it was computed in full and stored, and filters from the outer query could not be pushed into it, so the indexes inside could not be used. From PostgreSQL 12, a non-recursive, side-effect-free CTE referenced once is inlined and optimised like a subquery, which is why the upgrade restored the speed. A materialised CTE is still right when an expensive CTE is used several times, or when we deliberately want to fix the evaluation order; data-modifying CTEs always run once and fully.
Why this question is asked
This scenario is a classic because it punishes a good habit. Someone made a 300-line report readable by splitting it into CTEs, and on PostgreSQL 11 it became fifty times slower. Then an upgrade fixed it without a single change to the SQL. Interviewers ask about it to see whether we understand how the planner treats CTEs and whether we can read the evidence in a plan. In this answer, we will recap what an optimisation fence is, reproduce the slowdown, see what changed in PostgreSQL 12, learn how to read the plan, and then go through the cases where we still want materialisation.
1A Quick Recap of the Planner and Pushdown
When PostgreSQL plans a query, it is free to rearrange it as long as the result stays the same. One of its most useful moves is predicate pushdown: taking a filter written in the outer query and applying it as early as possible, ideally inside an index scan. If the outer query says WHERE region = 'EU', the planner wants to use an index on region to read only EU rows instead of reading everything and throwing most of it away.
An optimisation fence is a boundary the planner is not allowed to optimise across. Whatever is inside is planned on its own, executed in full, and its result is handed to the outer query as a finished set of rows.
2Reproducing the 50x Slowdown on PostgreSQL 11
Here is a simplified version of the report after it was split into CTEs. The outer query only wants one region and one week.
| Step | PostgreSQL 11 (fence) | PostgreSQL 12 and later (inlined) |
|---|---|---|
| Planning | CTE planned alone | CTE merged into the outer query |
| Filter region = 'EU' | Applied after the CTE is stored | Pushed down to the orders index scan |
| Rows produced by the join | 180 million | About 310 thousand |
| Temporary storage | Large, spills to disk | None |
| EXPLAIN shows | CTE Scan on order_lines | No CTE Scan node |
On PostgreSQL 11 the CTE was a fence. The database joined all 180 million order lines, wrote the result into a temporary store (spilling to disk because it was far larger than work_mem), and only then applied the region and date filter to the stored rows. The index on (region, created_at) was useless because the filter never reached the orders table.
The figures are illustrative, but the ratio is typical: when the outer filter keeps a small fraction of the data, a fence turns a targeted index lookup into a full computation, and a 50 times difference is easy to reach.
3What Changed in PostgreSQL 12
The fence was originally a deliberate guarantee: a CTE was evaluated once, exactly as written, which some people used as a hint to control the planner. In PostgreSQL 12 the default changed. A CTE is now inlined, that is, merged into the outer query and optimised like a subquery, when three conditions hold: it is not recursive, it has no side effects (it is a plain SELECT with no volatile functions such as random() or nextval()), and it is referenced exactly once in the rest of the statement.
Our order_lines CTE meets all three conditions, so on PostgreSQL 16 the planner pushes the region and date filter straight into the orders scan and uses the index. Nothing in the SQL changed; the planner simply stopped treating the CTE as a wall.
If a CTE is referenced two or more times, PostgreSQL 12 and later still materialise it by default, on the reasoning that computing it once is usually cheaper than computing it twice. We can override either default with AS MATERIALIZED or AS NOT MATERIALIZED.
4Reading the Plan: Is My CTE Materialised?
The quickest check is EXPLAIN. A materialised CTE appears as a separate section named after the CTE, and the outer query reads it through a CTE Scan node. An inlined CTE leaves no trace: we see the base tables and their index scans directly in the main plan.
Notice how the filter moved. In the materialised plan it sits on the CTE Scan, after the work is done. In the inlined plan it sits on the index scan, before the work starts. When we review a slow report, finding a CTE Scan with a selective filter on it is the clue that a fence is costing us.
5When a Materialised CTE Is Still the Right Choice
Materialisation is not bad; it is a tool. The first good use is reuse. If an expensive CTE, say an aggregate over 50 million rows, is referenced three times in one report, computing it once and reading the stored result three times is far cheaper than computing it three times. PostgreSQL already does this by default for multiple references, and we can keep it explicit with AS MATERIALIZED so a later edit does not change it.
The second use is controlling evaluation order when the planner chooses badly. Suppose the planner underestimates how many rows a complex filter returns and picks a nested loop that runs a million times. Writing the filter in a CTE AS MATERIALIZED forces PostgreSQL to compute that small set first and then join to it, and the planner sees the real row count of the stored result. It is a blunt tool, and we should leave a comment explaining why, because a future PostgreSQL version may plan the inlined form better.
The third case is not a choice at all. A data-modifying CTE, such as WITH d AS (DELETE FROM sessions WHERE expires_at < now() RETURNING *), is always executed exactly once and to completion, whether or not the main query reads all of its rows. PostgreSQL never inlines it, because its effect on the table is the point.
- Does it modify data or call volatile functions?YesAlways materialised, nothing to decideNoNext question
- Is it referenced more than once?YesMaterialise if it is expensiveNoNext question
- Does an outer filter need indexes inside it?YesLet it inline (default since 12)NoNext question
- Is the planner choosing a bad order?YesAS MATERIALIZED with a commentNoLeave the default
4 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Why did PostgreSQL keep the fence for so long?
Partly because it was documented behaviour that people relied on as a planner hint, and partly because guaranteeing single evaluation is simple and safe. Changing it risked making some existing queries slower. Version 12 changed the default and added AS MATERIALIZED so that anyone relying on the old behaviour could keep it explicitly.
Are recursive CTEs ever inlined?
No. A recursive CTE has to be evaluated iteratively, building a working table level by level, so it is always computed as its own step. Outer filters do not push into it, which is why we put the filter in the anchor part of the recursive CTE when we can.
How does MySQL compare?
MySQL 8.0 and later treat a CTE like a derived table. The optimiser can merge it into the outer query, which allows the outer conditions to use indexes, or materialise it, and in some versions it can also push conditions down into a materialised derived table. EXPLAIN shows which path it took, so the habit of reading the plan applies there too.
7Conclusion
In this answer, we saw that PostgreSQL 11 treated every CTE as an optimisation fence, computing it in full and blocking outer filters from reaching indexes inside, which made the split report fifty times slower. PostgreSQL 12 inlines non-recursive, side-effect-free CTEs referenced once, so the upgrade restored the indexed plan. A CTE Scan node in EXPLAIN shows materialisation, and we still choose it on purpose for expensive CTEs used several times or to fix a bad evaluation order, while data-modifying CTEs are always executed once and fully.
Open with
Before PostgreSQL 12, every CTE was an optimisation fence. The CTE was planned on its own, executed completely and stored, and the outer WHERE clause could not be pushed into it.
Then, if they want more
So when the report was split into CTEs, a filter like region equals EU and one week of dates was applied only after joining and storing every order line, and the indexes on orders could not be used. That easily costs fifty times.
From version 12, a CTE that is not recursive, has no side effects and is referenced only once is inlined and optimised like a subquery, so the filter goes back into the index scan, which is why the upgrade fixed it without touching the SQL.
I verify this with EXPLAIN: a CTE Scan node with the filter on it means it is materialised.
Materialisation is still the right choice when an expensive CTE is referenced several times, so it is computed once, or when I want to force the evaluation order because the planner picks a bad plan, and then I write AS MATERIALIZED with a comment. Data-modifying CTEs are always run once and completely regardless.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 12, PostgreSQL 11, PostgreSQL 16, MySQL 8.0
- 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.
- Official documentation
- PostgreSQL documentation, The SQL Language
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 "A report query got 50 times slower after someone split it into CTEs on PostgreSQL 11...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/80599db60c/