SQL 102· Level 4
CTEs (WITH)
Long queries are easier to read when they are broken into named steps. A CTE (common table expression) is a step with a name, written with WITH:
WITH unit_sizes AS ( SELECT ... ) SELECT ... FROM unit_sizes
- The query inside the brackets runs first. Its result behaves like a temporary table called
unit_sizes. - The final SELECT can then filter, join or group that result like any other table.
- For several steps, write
WITHonce and separate the steps with commas. A later step can use an earlier one.
AI assistants use CTEs heavily. To read one, go from top to bottom. For each step, work out what one row of its result stands for, then read the final SELECT.
To check a step, copy the query inside its brackets and run it on its own.
Worked example
On average, how many units has each student enrolled in, and what is the most?
WITH student_totals AS (
SELECT student_id, COUNT(*) AS units_taken
FROM enrolments
GROUP BY student_id
)
SELECT ROUND(AVG(units_taken), 1) AS average_units,
MAX(units_taken) AS most_units
FROM student_totalsGetting the practice database ready…
This takes a few seconds the first time. Nothing leaves your computer.