SQL · guide
CTE vs subquery in SQL: when to use which
A CTE names a query step so you can read the logic top to bottom. A subquery puts the same step inline.
The same query both ways
-- CTE WITH avg_kills AS ( SELECT AVG(kills) AS a FROM matches ) SELECT player_id FROM matches, avg_kills WHERE kills > a; -- Subquery SELECT player_id FROM matches WHERE kills > (SELECT AVG(kills) FROM matches);
When a CTE is better
- The query has several steps and you want to name each one.
- You reference the same intermediate result more than once.
- You need recursion (WITH RECURSIVE).
- You want to filter on a window function result: compute it in a CTE, filter outside.
When a subquery is fine
- A single small condition, like the example above.
- EXISTS and IN checks.
Performance
Do not assume a CTE is faster or slower. Some engines inline CTEs, others may materialise them, and this differs by database and version. Read the query plan (EXPLAIN) instead of guessing.