Guides / SQL

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

When a subquery is fine

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.

Practise it

Share on LinkedIn

Practise this for free

Run real code, get instant checks and keep your progress. Free to join with Google.

Start free → Choose a career path

More guides