MySQL Common Table Expressions
A common table expression (CTE) is a named, temporary result defined with WITH at the start of a statement. It does the same job as a derived table, but it is written before the main query, can be referenced several times, and can even refer to itself. MySQL supports CTEs since 8.0.
WITH cte_name AS (
SELECT ...
)
SELECT ... FROM cte_name ...;A first CTE
"Order totals, and the orders above the average total." With a CTE, the order totals are defined once and used twice:
WITH order_totals AS (
SELECT order_id, SUM(quantity * unit_price * (1 - discount)) AS total
FROM order_details
GROUP BY order_id
)
SELECT order_id, ROUND(total, 2) AS total
FROM order_totals
WHERE total > (SELECT AVG(total) FROM order_totals)
ORDER BY total DESC;+----------+-------+
| order_id | total |
+----------+-------+
| 4 | 59.00 |
| 15 | 36.50 |
| 14 | 35.21 |
| 10 | 34.38 |
| 1 | 33.80 |
| 19 | 32.45 |
| 5 | 32.30 |
| 3 | 28.77 |
| 11 | 27.15 |
+----------+-------+
The query reads top to bottom like a recipe: first compute the totals, then filter them. With derived tables, the same logic would have to be written twice, nested inside the main query.
Several CTEs
Separate multiple CTEs with commas. Each one can use those defined before it:
WITH
line_values AS (
SELECT o.customer_id, d.quantity * d.unit_price * (1 - d.discount) AS value
FROM orders AS o
JOIN order_details AS d ON d.order_id = o.order_id
WHERE o.status <> 'cancelled'
),
customer_revenue AS (
SELECT customer_id, SUM(value) AS revenue
FROM line_values
GROUP BY customer_id
)
SELECT c.first_name, c.last_name, ROUND(r.revenue, 2) AS revenue
FROM customer_revenue AS r
JOIN customers AS c ON c.customer_id = r.customer_id
ORDER BY r.revenue DESC
LIMIT 3;+------------+-----------+---------+
| first_name | last_name | revenue |
+------------+-----------+---------+
| Ana | Silva | 128.01 |
| Daniel | Weber | 55.92 |
| Elena | Rossi | 53.45 |
+------------+-----------+---------+
CTEs with window functions
CTEs pair naturally with window functions, since a window result often has to be filtered. The best-selling product (by units) in each category:
WITH product_units AS (
SELECT p.category_id, p.name, SUM(d.quantity) AS units
FROM products AS p
JOIN order_details AS d ON d.product_id = p.product_id
GROUP BY p.product_id, p.category_id, p.name
),
ranked AS (
SELECT category_id, name, units,
RANK() OVER (PARTITION BY category_id ORDER BY units DESC) AS pos
FROM product_units
)
SELECT category_id, name, units
FROM ranked
WHERE pos = 1
ORDER BY category_id, name;+-------------+------------------+-------+
| category_id | name | units |
+-------------+------------------+-------+
| 1 | Orange Juice 1L | 9 |
| 2 | Butter Croissant | 18 |
| 3 | Whole Milk 1L | 12 |
| 4 | Avocado (each) | 10 |
| 5 | Sea Salt Crisps | 12 |
| 6 | Dish Soap 500ml | 5 |
+-------------+------------------+-------+
Recursive CTEs
A recursive CTE refers to itself. It has two parts joined by UNION ALL: an anchor query that produces the starting rows, and a recursive query that produces new rows from the previous ones. Recursion stops when the recursive part returns no rows.
A simple example generates a series of numbers:
WITH RECURSIVE numbers (n) AS (
SELECT 1 -- anchor
UNION ALL
SELECT n + 1 FROM numbers -- recursive step
WHERE n < 5
)
SELECT n, n * n AS square FROM numbers;+------+--------+
| n | square |
+------+--------+
| 1 | 1 |
| 2 | 4 |
| 3 | 9 |
| 4 | 16 |
| 5 | 25 |
+------+--------+
The same trick fills gaps in data, for example to list every month, including months without orders:
WITH RECURSIVE months (m) AS (
SELECT DATE '2025-01-01'
UNION ALL
SELECT m + INTERVAL 1 MONTH FROM months WHERE m < '2025-08-01'
)
SELECT DATE_FORMAT(months.m, '%Y-%m') AS month, COUNT(o.order_id) AS orders
FROM months
LEFT JOIN orders AS o
ON o.order_date >= months.m AND o.order_date < months.m + INTERVAL 1 MONTH
GROUP BY months.m
ORDER BY months.m;+---------+--------+
| month | orders |
+---------+--------+
| 2025-01 | 4 |
| 2025-02 | 4 |
| 2025-03 | 4 |
| 2025-04 | 4 |
| 2025-05 | 4 |
| 2025-06 | 2 |
| 2025-07 | 0 |
| 2025-08 | 0 |
+---------+--------+
Walking a hierarchy
Recursive CTEs shine on tree-shaped data like the employees' management chain. Start with the CEO (no manager), then repeatedly add the people who report to someone already found:
WITH RECURSIVE org (employee_id, name, title, level, path) AS (
SELECT employee_id, first_name, title, 1, CAST(first_name AS CHAR(200))
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.first_name, e.title, org.level + 1,
CONCAT(org.path, ' > ', e.first_name)
FROM employees AS e
JOIN org ON e.manager_id = org.employee_id
)
SELECT CONCAT(REPEAT(' ', level - 1), name) AS org_chart, title, path
FROM org
ORDER BY path;+---------------+-------------------+----------------------+
| org_chart | title | path |
+---------------+-------------------+----------------------+
| Grace | CEO | Grace |
| Ada | Warehouse Manager | Grace > Ada |
| Sara | Packer | Grace > Ada > Sara |
| Tom | Packer | Grace > Ada > Tom |
| Alan | Sales Manager | Grace > Alan |
| Linus | Sales Rep | Grace > Alan > Linus |
| Maya | Sales Rep | Grace > Alan > Maya |
| Omar | Sales Rep | Grace > Alan > Omar |
+---------------+-------------------+----------------------+
The anchor's CAST(... AS CHAR(200)) matters: the column types of a recursive CTE are fixed by the anchor, so without it path would be only as wide as the longest first name and the longer paths would not fit.
Note: MySQL stops runaway recursion after
cte_max_recursion_depthiterations (1000 by default) with an error. Always make sure the recursive part eventually returns no rows.
Test yourself
Which keyword starts a common table expression?
- CTE
- WITH
- DEFINE
- TEMP
What are the two parts of a recursive CTE?
- SELECT and WHERE
- An anchor query and a recursive query joined with UNION ALL
- Two CTEs separated by a comma
- A procedure and a trigger
Can a CTE be referenced more than once in the main query?
- No, only once
- Yes
- Only if it is recursive
- Only in MySQL 5.7