SQL CTE (WITH Clause)
A CTE, or common table expression, names a query with WITH so you can use it like a table in the query that follows. It turns nested subqueries into readable steps.
Updated December 1, 2026
Syntax
WITH step_name AS (
SELECT ...
)
SELECT ...
FROM step_name;
Name a step
First total each order, then find the big ones. Cancelled orders are left out.
WITH order_totals AS (
SELECT o.id, o.customer_id, SUM(i.quantity * p.price) AS total
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.id
JOIN products AS p ON p.id = i.product_id
WHERE o.status <> 'cancelled'
GROUP BY o.id, o.customer_id
)
SELECT id, total
FROM order_totals
WHERE total > 50
ORDER BY total DESC;
| id | total |
|---|---|
| 8 | 338 |
| 4 | 249 |
| 2 | 89 |
| 10 | 57 |
| 6 | 54 |
Chain several CTEs
Separate CTEs with commas. Each one can use the ones before it. Here: department averages, then everyone paid above their department’s average.
WITH dept_avg AS (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
),
above AS (
SELECT e.name, e.salary, ROUND(d.avg_salary) AS dept_avg
FROM employees AS e
JOIN dept_avg AS d ON d.department_id = e.department_id
WHERE e.salary > d.avg_salary
)
SELECT * FROM above
ORDER BY salary DESC;
| name | salary | dept_avg |
|---|---|---|
| Omar Haddad | 215000 | 163000 |
| Maya Chen | 210000 | 163000 |
| Jack Miller | 160000 | 103750 |
| Diego Alvarez | 130000 | 100000 |
| Farah Khan | 90000 | 66667 |
Common mistakes
- Putting a comma after the last CTE, right before the main
SELECT. - Writing
WITHbefore each CTE. UseWITHonce, then commas. - Expecting a CTE to persist. It only exists for the single statement that follows it.
Practice CTE (WITH Clause) interactively
Write real queries in your browser and get instant feedback in the lesson “WITH (CTEs)” (Unit 6). New learners can start free from the first lesson.
Frequently asked questions
CTE vs subquery: which should I use?
They usually perform the same. Use a CTE when the logic has steps, or when you need the same result twice in one query.
What is a recursive CTE?
WITH RECURSIVE lets a CTE refer to itself, which is useful for hierarchies like an org chart or for generating series of dates.