Quick revision
The short answer
Since PostgreSQL 12, a non-recursive, side-effect-free CTE that is referenced once is inlined into the main query instead of being computed separately. That usually helps, because outer conditions can be pushed into it, which is why other queries got faster, but for some queries the combined plan is worse, for example through a bad row estimate or repeated expensive work. We control it per CTE with WITH recent AS MATERIALIZED (...) to restore the old fence, or NOT MATERIALIZED to force inlining, after comparing EXPLAIN ANALYZE of both and making sure the upgraded database has fresh statistics.
What to remember
In this answer, we saw that PostgreSQL 12 changed non-recursive, side-effect-free CTEs referenced once from always materialised to inlined, which speeds up most queries by pushing filters inside, but can produce worse plans when estimates are off or work is repeated. We confirmed the cause by comparing EXPLAIN ANALYZE with AS MATERIALIZED, fixed the query with MATERIALIZED or better statistics, and ran ANALYZE after pg_upgrade and pg_stat_statements comparisons to catch regressions early.
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.
Since PostgreSQL 12, a non-recursive, side-effect-free CTE that is referenced once is inlined into the main query instead of being computed separately. That usually helps, because outer conditions can be pushed into it, which is why other queries got faster, but for some queries the combined plan is worse, for example through a bad row estimate or repeated expensive work. We control it per CTE with WITH recent AS MATERIALIZED (...) to restore the old fence, or NOT MATERIALIZED to force inlining, after comparing EXPLAIN ANALYZE of both and making sure the upgraded database has fresh statistics.
Why this question is asked
Major version upgrades usually make most queries faster and a few slower, and the slower ones are what users notice. The CTE change in PostgreSQL 12 is one of the most famous causes, because it changed how a common query style is optimised without any change to the SQL. Interviewers ask this to see whether we know the change, can show it in a plan, can fix the specific query without undoing the benefit elsewhere, and run upgrades in a way that catches these regressions early. In this answer, we will recap what a CTE fence was, see what changed, reproduce a regression, fix it, and set up the upgrade checks that find such queries before users do.
1A Quick Recap: CTEs as Optimisation Fences
Up to PostgreSQL 11, every CTE was materialised. PostgreSQL computed the CTE's query on its own, stored the result in memory or a temp file, and then ran the main query against that stored result. Nothing from the main query could get inside: a WHERE condition on the CTE's result could not be pushed down to use an index in the CTE, and the planner could not join the CTE's tables in a different order. People called this an optimisation fence.
Teams learned to use it on purpose. If the planner chose a bad plan for a big query, wrapping part of it in a CTE forced it to compute that part first, often a small filtered set, and then join. Many queries written on PostgreSQL 9 to 11 rely on that behaviour without saying so.
2What Changed in PostgreSQL 12
Since PostgreSQL 12, a CTE is inlined into the main query, treated like a subquery in FROM, when it is not recursive, has no side effects such as data-modifying statements or volatile functions, and is referenced only once. The planner then optimises the whole statement together. A CTE referenced twice or more is still materialised by default, to avoid computing it twice. Two keywords let us override the default per CTE: AS MATERIALIZED keeps the old fence, and AS NOT MATERIALIZED asks for inlining even when it is referenced more than once.
This is why most CTE queries got faster after the upgrade: the filter on account 42 is now applied inside, using a better index, instead of after computing a whole day of events.
3How Inlining Can Make a Query Slower
Inlining gives the planner more freedom, and occasionally it uses that freedom badly. The typical case is a CTE that produces a small, well-understood set, followed by joins to large tables. On PostgreSQL 11, the CTE was computed first, and the joins started from its actual result. After inlining, the planner estimates the combined conditions, and if its estimate is far off, for example because the columns are correlated or the condition uses a function, it may choose a nested loop that runs millions of times, or start the join from the wrong table.
| PostgreSQL 11 | PostgreSQL 12 and later | |
|---|---|---|
| CTE used once | Materialised: computed first, then scanned | Inlined into the main query |
| Outer filters | Applied after the CTE result | Pushed down into it, indexes usable |
| Join order | CTE result first | Planner chooses freely |
| Typical effect | Predictable, sometimes wasteful | Usually faster, sometimes a bad estimate |
| Override | Not needed | AS MATERIALIZED / AS NOT MATERIALIZED |
Other causes exist too. If an expensive function was called in the CTE's select list, inlining can place it where it runs more often than before. And a CTE that used to be computed once but is now inlined into a correlated position may be recomputed per row. In each case, the SQL did not change; only the optimiser's freedom did.
4Fixing the Slow Query
First we confirm the cause instead of assuming it. We run EXPLAIN (ANALYZE, BUFFERS) for the query as it is, then the same query with AS MATERIALIZED added, and compare. If the materialised version brings back the old plan and time, inlining is the cause.
AS MATERIALIZED is a precise, documented fix: it affects only this CTE and only this query, and it states the intent in the SQL. But it is worth asking why the inlined plan was bad. If the estimate was wrong because of correlated columns, extended statistics may fix it, and then the inlined plan may be even faster than the old one. Using MATERIALIZED on every CTE in the codebase would throw away the improvements that made other queries faster, so we apply it only where measurements show a regression.
5Running Upgrades So Regressions Are Found Early
There is an even more common cause of slowness right after an upgrade that we must rule out first: missing statistics. pg_upgrade does not carry the planner statistics over to the new cluster, so until ANALYZE runs, the planner works with defaults and many plans are poor. The documented step is vacuumdb --all --analyze-in-stages right after the upgrade. Only when statistics are fresh is a remaining slow query a real regression.
To find regressions systematically, we record pg_stat_statements on the old version for a week before the upgrade and compare after: calls, mean_exec_time and shared block reads per query. Match queries by their normalised text rather than queryid, since ids are not guaranteed to stay the same across major versions, and note that column names changed in version 13, total_time became total_exec_time. Better still, replay the top queries against an upgraded copy of production before the real upgrade, and compare plans and timings. The slow CTE would then have been fixed before any user saw it.
- Record pg_stat_statements on the old versiona week of real traffic
- Upgrade a copy and run ANALYZEvacuumdb --all --analyze-in-stages
- Replay top queries and comparemean time, buffers, plans
- Regression found?YesCompare with AS MATERIALIZED, fix estimatesNoUpgrade production
- Re-check pg_stat_statements after go-live
5 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Why are CTEs referenced twice still materialised by default?
Because inlining would duplicate the query: each reference would compute the CTE again. Materialising it once and reading the result twice is usually cheaper. If the CTE is cheap and each reference is filtered differently, NOT MATERIALIZED can be faster, since each copy can use its own index; that is a case-by-case decision based on EXPLAIN ANALYZE.
Are there CTEs that PostgreSQL never inlines?
Yes. Recursive CTEs, CTEs containing data-modifying statements such as INSERT ... RETURNING, CTEs that call volatile functions, and, by default, CTEs referenced more than once. Those behave as they did on PostgreSQL 11.
How would you prevent the team from relying on fences without saying so?
By making intent explicit: any CTE used as a fence should say AS MATERIALIZED with a short comment explaining why. Code review and an upgrade checklist can include a search for queries tuned on older versions. Then the next upgrade does not change behaviour silently, because the SQL already states what it needs.
7Conclusion
In this answer, we saw that PostgreSQL 12 changed non-recursive, side-effect-free CTEs referenced once from always materialised to inlined, which speeds up most queries by pushing filters inside, but can produce worse plans when estimates are off or work is repeated. We confirmed the cause by comparing EXPLAIN ANALYZE with AS MATERIALIZED, fixed the query with MATERIALIZED or better statistics, and ran ANALYZE after pg_upgrade and pg_stat_statements comparisons to catch regressions early.
Open with
The change is CTE inlining. Up to PostgreSQL 11, every CTE was materialised, computed on its own and stored, so it acted as an optimisation fence. Since 12, a non-recursive CTE without side effects that is referenced once is inlined into the main query and optimised together with it.
Then, if they want more
That is why most queries got faster: outer filters are pushed inside and better indexes get used. But for some queries the extra freedom leads to a worse plan.
Typically the CTE produced a small set that was joined to big tables; after inlining, the planner misestimates the combined conditions, picks a nested loop or the wrong join order, and the query goes from 100 milliseconds to many seconds.
Before blaming that, I would make sure statistics exist, because pg_upgrade does not carry them over, so vacuumdb analyze-in-stages has to run after the upgrade. Then I would run EXPLAIN ANALYZE with BUFFERS for the query as is and with WITH recent AS MATERIALIZED.
If the materialised version restores the old plan, I keep MATERIALIZED for that CTE, with a comment, or better fix the estimate, for example with extended statistics on correlated columns. NOT MATERIALIZED is the opposite switch, forcing inlining. I would not add MATERIALIZED everywhere, since that undoes the gains.
For the process, I would compare pg_stat_statements from before and after, matching by query text, and replay top queries on an upgraded copy before production.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 11, PostgreSQL 12, PostgreSQL 17, PostgreSQL 9
- 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 "After upgrading from PostgreSQL 11 to 17, a query using WITH recent AS (SELECT ... FROM...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/e8712eab14/