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;
Result on the Desk & Co. (online store) sample data (5 rows)
idtotal
8338
4249
289
1057
654

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;
Result on the Acme Co. (company data) sample data (5 rows)
namesalarydept_avg
Omar Haddad215000163000
Maya Chen210000163000
Jack Miller160000103750
Diego Alvarez130000100000
Farah Khan9000066667

Common mistakes

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.

Related SQL tutorials