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.
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.
| teamtext | nbigint | avg_pointsnumeric |
|---|---|---|
| Red | 3 | 27.5 |
| Blue | 3 | 17 |
| Green | 2 | 32 |
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.
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.