Learning navigation

Code with Animation

Common Table Expressions (WITH)

Name each step of a long query with WITH, read it from top to bottom, and reuse a step more than once.

SQL5 min readConcept 25 of 44

Name a step, then use it

A common table expression (CTE) gives a name to a subquery. You write it with WITH name AS (query) before the main query, then use the name as if it were a table.

The manual describes a CTE as a temporary table that exists for just one query. You can write several, separated by commas, and a later one may use an earlier one.

Readable queries

Nested subqueries must be read from the inside out. A chain of CTEs reads from top to bottom, like steps in a recipe, and each step can be tested on its own.

Two steps, then the answer

WITH team_stats AS (
  SELECT team, count(*) AS n, round(avg(points), 1) AS avg_points
  FROM players
  GROUP BY team
), busy AS (
  SELECT team, n FROM team_stats WHERE n >= 3
)
SELECT team FROM busy ORDER BY team;

team_stats has one row per team: Red 3, Blue 3, Green 2. busy reads it by name and keeps the teams with at least 3 players: Red and Blue. The final SELECT reads busy.

A name can be used more than once in the main query, for example to compare each team with the average of all teams. You do not have to repeat the subquery text.

Walk through the steps

Press each step to see the table it produces, change the threshold, and switch on Without WITH to compare the nested version.

WITH team_stats AS (
SELECT team, count(*) AS n,
round(avg(points), 1) AS avg_points
FROM players
GROUP BY team
), busy AS (
SELECT team, n FROM team_stats WHERE n >= 3
)
SELECT team FROM busy
ORDER BY team;
team_stats (3 rows)
teamtextnbigintavg_pointsnumeric
Red327.5
Blue317
Green232

The first CTE is a named result: one row per team, with its count and average. It exists only for this one query.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1How long does a CTE named `busy` exist?
  2. 2In `WITH a AS (...), b AS (SELECT * FROM a WHERE ...) SELECT * FROM b`, can `b` use `a`?
  3. 3What is the main benefit of a CTE compared with a nested subquery?

Remember this

  • WITH name AS (query) gives a subquery a name for the rest of one statement.
  • Several CTEs are separated by commas, and a later one can use an earlier one.
  • A CTE exists only for its own statement. It is not saved.
  • A CTE is for readability. The result is the same as the nested version.

Done with this concept?

Mark it complete to track your progress. No login needed.