A SQL CTE (common table expression) is a temporary, named result that you define with the WITH clause and then use like a table in the rest of the query. It lets you split a long query with nested subqueries into named steps. The query then reads from top to bottom like a short story.
The examples use the Northbridge University database from the SQL course: enrollment (exam scores per student and course offering), student and course.
How do you write a query with the WITH clause?
Question: which students scored above the average midterm of their own course offering? You need two steps. First, find the average for each offering. Second, compare every score with the average of its offering.
WITH offering_avg AS ( SELECT offering_id, AVG(midterm) AS avg_midterm FROM enrollment WHERE offering_id IN (3, 4) GROUP BY offering_id ) SELECT s.first_name || ' ' || s.last_name AS student, e.offering_id, e.midterm, ROUND(a.avg_midterm, 1) AS offering_avg FROM enrollment e JOIN offering_avg a ON a.offering_id = e.offering_id JOIN student s ON s.id = e.student_id WHERE e.midterm > a.avg_midterm ORDER BY e.offering_id, e.midterm DESC;
| student | offering_id | midterm | offering_avg |
|---|---|---|---|
| Kenji Park | 3 | 88 | 78.0 |
| Liam Johansson | 4 | 95 | 86.8 |
| Diego Haddad | 4 | 87 | 86.8 |
Read it like this: "First build a temporary table called offering_avg with the average midterm of each offering. Then join the scores to it and keep the ones above the average."
What is the difference between a CTE and a subquery?
You can get the same result with a subquery inside FROM:
SELECT s.first_name || ' ' || s.last_name AS student, e.offering_id, e.midterm, ROUND(a.avg_midterm, 1) AS offering_avg FROM enrollment e JOIN ( SELECT offering_id, AVG(midterm) AS avg_midterm FROM enrollment WHERE offering_id IN (3, 4) GROUP BY offering_id ) a ON a.offering_id = e.offering_id JOIN student s ON s.id = e.student_id WHERE e.midterm > a.avg_midterm ORDER BY e.offering_id, e.midterm DESC;
The result is the same three rows. The difference is readability. The subquery sits in the middle of the main query. The CTE has a name and comes first. With more steps, the difference grows.
| Situation | Use a CTE? |
|---|---|
| Two or three nested subqueries | Yes, split them into steps |
| You need the same intermediate result twice | Yes, define it once |
| A short one-line subquery | Not needed |
| Someone else will read the report | Yes, the step names explain the logic |
Can you chain more than one CTE?
Yes. Separate CTEs with commas, write WITH only once, and let each CTE use the ones before it. This query finds students whose average midterm is at least 95, ignoring students with fewer than 3 scores:
WITH student_avg AS ( SELECT student_id, AVG(midterm) AS avg_midterm, COUNT(*) AS n FROM enrollment GROUP BY student_id ), strong AS ( SELECT student_id, avg_midterm FROM student_avg WHERE avg_midterm >= 95 AND n >= 3 ) SELECT s.first_name || ' ' || s.last_name AS student, ROUND(st.avg_midterm, 1) AS avg_midterm FROM strong st JOIN student s ON s.id = st.student_id ORDER BY st.avg_midterm DESC, student;
| student | avg_midterm |
|---|---|
| Zara Larsen | 99.1 |
| Kenji Silva | 97.9 |
| Ali Rossi | 96.5 |
| Emeka Okafor | 95.1 |
Each step does one job: average per student, then the filter, then the names.
If a result looks wrong, change the final query to look inside one step:
WITH student_avg AS ( SELECT student_id, AVG(midterm) AS avg_midterm, COUNT(*) AS n FROM enrollment GROUP BY student_id ) SELECT student_id, n, ROUND(avg_midterm, 1) AS avg_midterm FROM student_avg WHERE student_id <= 5 ORDER BY student_id;
| student_id | n | avg_midterm |
|---|---|---|
| 1 | 6 | 90.0 |
| 2 | 7 | 93.6 |
| 3 | 3 | 60.0 |
| 4 | 9 | 78.8 |
| 5 | 8 | 70.5 |
With nested subqueries you would have to take the query apart to do this check.
What is a recursive CTE?
A recursive CTE refers to itself, so it can follow a chain of any length. In the course table, each course can point to a prerequisite course. This query lists the whole chain behind Data Structures (course id 8):
WITH RECURSIVE chain AS ( SELECT id, code, name, prerequisite_id, 1 AS step FROM course WHERE id = 8 UNION ALL SELECT c.id, c.code, c.name, c.prerequisite_id, chain.step + 1 FROM course c JOIN chain ON c.id = chain.prerequisite_id ) SELECT step, code, name FROM chain ORDER BY step;
| step | code | name |
|---|---|---|
| 1 | SWE201 | Data Structures |
| 2 | SWE102 | Object-Oriented Programming |
| 3 | SWE101 | Introduction to Programming |
The part before UNION ALL is the starting row. The part after it runs again and again, each time using the rows found in the previous round, and stops when no new row is found. Introduction to Programming has no prerequisite, so the chain ends there.
Things to know
- A CTE lives only for the one query that defines it. It does not create a table.
- If you want to reuse a query many times, create a view instead.
Common mistakes
- Missing comma between CTEs: write a comma before the second CTE, and
WITHonly once. - A semicolon after the CTE:
WITH ... AS (...);ends the statement, and the main query can no longer see the CTE. PostgreSQL answerssyntax error at or near ";". - No main query: a CTE cannot run alone. A
SELECThas to follow it.
What to read next
- [CTE and WITH](/learn/sql/cte-with): build student records reports step by step in the browser.
- [SQL window functions explained](/blog/sql-window-functions): a related tool for ranking and running totals.
- [SQL for beginners: the full course](/courses/sql)
- #sql
- #cte
- #with clause
- #subquery