5 MIN · 2026-10-31

CTE vs subquery: when to use each

Both express the same idea. Use a subquery for one quick lookup, a CTE when the result has a name or is needed twice — with examples from the course.

CTE vs subquery: when to use each

A subquery and a CTE can express the same thing. The choice is mostly about readability — and about whether you need to use the same result twice.

A subquery is enough for one use

This query compares every track with the average price:

SELECT title, unit_price
FROM tracks
WHERE unit_price > (SELECT AVG(unit_price) FROM tracks)
ORDER BY unit_price DESC, title;

The inner SELECT runs once and produces a single number. The outer query uses it and moves on. There is no name to invent and no reason to make the query longer. A scalar subquery is the right tool.

A CTE names the intermediate result

When the intermediate result is a table, name it:

WITH track_counts AS (
  SELECT album_id, COUNT(*) AS tracks
  FROM tracks
  GROUP BY album_id
)
SELECT a.title, tc.tracks
FROM albums a
JOIN track_counts tc ON tc.album_id = a.id
WHERE tc.tracks >= 3
ORDER BY a.title
LIMIT 8;

track_counts reads like a step in a recipe: first count tracks per album, then join that result to albums. The database does the same work either way; the CTE makes the shape of the query obvious.

The case that decides it: reuse

Here is a question that needs the same result twice: which genre has the most tracks?

WITH genre_counts AS (
  SELECT genre_id, COUNT(*) AS tracks
  FROM tracks
  GROUP BY genre_id
)
SELECT g.name, gc.tracks
FROM genres g
JOIN genre_counts gc ON gc.genre_id = g.id
WHERE gc.tracks = (SELECT MAX(tracks) FROM genre_counts);

genre_counts is used in the join and again in the scalar subquery. With a plain subquery you would either repeat the GROUP BY or nest it twice. The CTE keeps one definition.

Recursive queries need a CTE

Some results are defined in terms of themselves — an org chart, a category tree, a sequence of numbers. SQLite spells that WITH RECURSIVE:

WITH RECURSIVE nums(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM nums WHERE n < 5
)
SELECT n FROM nums;

There is no subquery equivalent. If the problem is recursive, the CTE is not a style choice; it is the only way.

Rules of thumb

  • One quick lookup → subquery.
  • A result with a name, or used twice → CTE.
  • More than two levels of nesting → CTE.
  • Recursive → WITH RECURSIVE.
  • A CTE that is used once and makes the query harder to read → just use a subquery.

Keep exploring: the CTEs and capstone chapter covers WITH, recursive queries and a final project that combines everything.

Keep learning