r/Database • u/shdw_0x0 • 18d ago
Why does a query with a CTE sometimes take forever to execute?
I've noticed that some SQL queries using WITH clauses (CTEs) take significantly longer to execute than expected, especially when multiple CTEs are chained together.
I understand that a CTE is mainly used to organize complex queries and make them easier to read, but I'm curious about what happens behind the scenes.
Does the database execute each CTE separately, or does it optimize everything into a single execution plan? Can CTE materialization, repeated references, or joins between multiple CTEs cause performance issues?
I'd be interested to hear about real cases where replacing a CTE with a subquery or temporary table actually improved query performance.
Which database are you using, and have you run into this issue?
11
u/mattbillenstein 18d ago
explain analyze ...
It's not the CTE, it's probably the subqueries chaining without the proper indexes to make them fast. Look for table scans where an index would massively limit the number of rows the query needs to look at - table scans on very small tables are usually fine.
1
u/Rare_Comfortable88 14d ago
define “very small tables”
1
u/mattbillenstein 14d ago
I'd expect not too much trouble with a few thousand rows, but I've not done any specific benchmarks and it's probably workload/system dependent.
4
u/Aggressive_Ad_5454 18d ago
Every DBMS I've worked with (SQL Server, MariaDb/MySQL, PostgreSQL, and Oracle a long time ago) generates one single execution plan for each whole query, including CTEs and view objects, as well as tables.
There's not much worthwhile to say generally about why queries with CTEs are slow. It's often because some step of the plan has to do a nasty slow operation like a full table scan or full index scan, or because it has to iterate a step many thousands of times.
Look at the execution plan. Misquoting Tolstoy: All fast queries are the same. Each slow query is slow in its own way.
3
u/Far_Swordfish5729 18d ago
A CTE (and a subquery) are logical parentheses and nothing more. The engine considers the entire query. Now in the query plan you are likely to see a group that is clearly the CTE, but that’s the logical result you asked for incorporated into a larger plan. Asking why it performs poorly is about asking why that plan performed poorly.
Usually, the answer to that question is indexing - it was not possible to find the data efficiently - or statistics - the engine picked the wrong search predicate or retrieval order based on a bad estimate of output cardinality (what would reduce row count the fastest). Those estimates and actual row counts are often visible in the executed plan. If they’re far off, updating table stats can get you a much better plan next time.
Temp tables come into play when a reusable, indexed intermediate result dramatically improves the plan and the engine isn’t getting there. It often happens when a data circumstance means you could create a temporary composite index for future seeks that’s really helpful. You might also need an initial, expensive result set in multiple steps and the engine keeps recalculating it each time. Note that the engine can use temp tables called table spools in the plan. It just sometimes doesn’t or its choice is bad. Remember to update stats on your temp table after insert to avoid bad engine decisions.
2
u/slyiscoming 18d ago
Look at the plan. It can be a lot of things.
Look for loops and scans, then find ways to remove them.
1
u/tm604 18d ago
Which database are you seeing the slow performance on, what were the queries, what were the execution plans...?
Old versions of PostgreSQL (pre-12) used to materialise CTE clauses, for example:
https://git.postgresql.org/gitweb/?p=postgresql.git;a=commitdiff;h=608b167f9
so yes, it's possible for a specific version of a database engine to lack some specific CTE optimisations. "My query is slow because I used a CTE" is usually not a good starting point, however...
1
u/No_Witness_5295 18d ago
CTEs shine when you use nested CTEs. they should also be precise in scope and not do too much. there's no reason to force them where they are not needed.
1
u/nborwankar 18d ago
The WITH clauses may be creating large in-memory temp tables that create memory contention.
1
u/phesago 14d ago
" Can CTE materialization, repeated references, or joins between multiple CTEs cause performance issues?"
cte's dont materialize - they recompile on run time
Yes. Bad habits/anti patterns + cte's = bad time (no pun intended).
So, past answering your direct questions, Ill take a bit to respond to more:
I whole heartedly reject that cte's make things more readable. If you honestly think so, then Im guessing you dont really work with sql on the day to day.
Temp tables are 99% of the time more preferable. you can index them. And theyre actually an object. Thats a big upgrade
Cte's, due to the way they work, will often magnify a problem with queries due to how they recompile everytime you reference them. This directly implies JOINs, Aggregates (especially in JOINs to Cte with Aggs), and Nested Cte's in a JOIN stack. Basically, you see this insane amount of churn, seemingly super simple queries. Knowing how they interact with other features/techniques, and understanding how those things work as well, will lead you to understand why it often ends up being a bad choice.
If it helps, I try not to use them. I do implement recursive ones sometimes but it isnt often (mainly because loops might be less cpu intensive). At my current job, we call out cte's in code reviews. Most of the time they are requested to be changed by the author of said code.
1
u/geofft 12d ago
I've seen devs use CTEs to make writing queries more like procedural languages with functions, DRY etc. I've seen those same queries take hours to execute instead of milliseconds because the engine loses the plot and decided to execute the cte per row instead of seeing the possible set operations.
It's generally not the fault of the CTE.
0
u/navicat-gu 17d ago
Short answer: a CTE is not automatically a temp table. Whether it's inlined into one plan or materialised (computed once and stored) depends on the engine and version — and that choice is usually why "WITH makes it slow."
What happens behind the scenes
PostgreSQL: historically materialised CTEs by default (optimisation fence). From PG 12+ the planner can inline non-recursive CTEs, and you can force it with
AS NOT MATERIALIZED/AS MATERIALIZED. A materialised CTE that is only used once, or that blocks predicate pushdown, is a classic footgun.MySQL 8: CTEs are usually merged/inlined when safe; recursive CTEs are different. Repeated references and big intermediate results still hurt.
SQL Server: similar story — can spool/materialise; hints exist.
When CTEs get slow
Referenced more than once → engine may compute the CTE once (good) or re-run it (bad), or materialise a huge set you only needed filtered.
Filters applied outside the CTE → if materialised, the CTE builds the full set before
WHERE/LIMITon the outer query.Chained CTEs where each step is
SELECT * FROM prevplus a join — readability wins, the planner may lose join-reorder freedom across the fence.Accidental cross joins / fan-out hidden inside a "clean" CTE.
How to check
EXPLAIN (ANALYZE, BUFFERS)
-- Postgres
-- or EXPLAIN ANALYZE in MySQL 8.0.18+Look for a Materialize / spool node on the CTE, row estimates that are wildly wrong, and whether your WHERE was pushed into the CTE.
Fixes that usually work
Push filters into the CTE.
In Postgres: try
AS NOT MATERIALIZED(or the opposite if you reference it many times and want one compute).Replace a one-shot CTE with a subquery, or the other way around, and compare plans.
For truly reused heavy intermediates, an explicit temp table with an index can be faster and clearer than hoping the CTE materialises well.
Disclosure: I'm RC, Director of Digital Strategy @ Navicat. For reading plans, Navicat 18 has a visual explain feature (paid); EXPLAIN ANALYZE in the client of your choice (Premium Lite's query editor is free) is enough to see the materialize-vs-inline question.
31
u/FirmAndSquishyTomato 18d ago
Why not look at the query plan? Then you will know what the database engine is doing behind the scenes.
Your poor results are not from the fact you are using a cte.