MySQL CTEs, Recursive Queries and UNION, INTERSECT, EXCEPT

MySQL 65 min min read Updated: Nov 27, 2026 Intermediate
MySQL CTEs, Recursive Queries and UNION, INTERSECT, EXCEPT
Intermediate Topic 3 of 3

A Simple CTE

A Common Table Expression gives a subquery a name so the main query reads top to bottom:

sql WITH spend AS ( SELECT o.customer_id, SUM(oi.quantity * p.price) AS total FROM orders o JOIN order_items oi ON oi.order_id = o.id JOIN products p ON p.id = oi.product_id WHERE o.status <> 'cancelled' GROUP BY o.customer_id ) SELECT c.name, ROUND(s.total, 2) AS total FROM spend s JOIN customers c ON c.id = s.customer_id ORDER BY s.total DESC;

Result:

nametotal
Asha Rao1349.00
Eli Brown989.00
Chen Wei706.00
Fatima Khan678.00
Ben Carter659.00

Several CTEs

sql WITH big_orders AS (SELECT order_id, SUM(quantity) AS items FROM order_items GROUP BY order_id HAVING SUM(quantity) >= 3), names AS (SELECT o.id, c.name FROM orders o JOIN customers c ON c.id = o.customer_id) SELECT n.name, b.order_id, b.items FROM big_orders b JOIN names n ON n.id = b.order_id ORDER BY b.order_id;

Result:

nameorder_iditems
Asha Rao13
Asha Rao214
Chen Wei43
Eli Brown63
Asha Rao73
Chen Wei821
Ben Carter1012

Recursive CTE: Number Series

sql WITH RECURSIVE n AS (SELECT 1 AS i UNION ALL SELECT i + 1 FROM n WHERE i < 5) SELECT i, i * i AS square FROM n;

Result:

isquare
11
24
39
416
525

The first part is the anchor, the second part refers to the CTE itself. It stops when the WHERE fails. A safety limit cte_max_recursion_depth (1000 by default) stops runaway queries:

sql WITH RECURSIVE n AS (SELECT 1 AS i UNION ALL SELECT i + 1 FROM n) SELECT COUNT(*) FROM n;
Error

ERROR 3636: Recursive query aborted after 1001 iterations. Try increasing @@cte_max_recursion_depth to a larger value.

Recursive CTE: Org Chart

sql CREATE TABLE staff (id INT PRIMARY KEY, name VARCHAR(20), manager_id INT); INSERT INTO staff VALUES (1, 'Zara', NULL), (2, 'Yusuf', 1), (3, 'Xin', 1), (4, 'Wale', 2), (5, 'Vik', 4); WITH RECURSIVE tree AS ( SELECT id, name, 0 AS depth, CAST(name AS CHAR(200)) AS path FROM staff WHERE manager_id IS NULL UNION ALL SELECT s.id, s.name, t.depth + 1, CONCAT(t.path, ' > ', s.name) FROM staff s JOIN tree t ON s.manager_id = t.id ) SELECT CONCAT(REPEAT(' ', depth), name) AS org, path FROM tree ORDER BY path;

Result:

orgpath
ZaraZara
XinZara > Xin
YusufZara > Yusuf
WaleZara > Yusuf > Wale
VikZara > Yusuf > Wale > Vik
Cast the path column The anchor decides the column width. Without CAST(name AS CHAR(200)) a long path would be cut or fail in strict mode.

Recursive CTE: Fill Date Gaps

sql WITH RECURSIVE days AS (SELECT DATE('2025-03-01') AS d UNION ALL SELECT d + INTERVAL 1 DAY FROM days WHERE d < '2025-03-05') SELECT days.d, COUNT(o.id) AS orders FROM days LEFT JOIN orders o ON o.order_date = days.d GROUP BY days.d ORDER BY days.d;

Result:

dorders
2025-03-011
2025-03-020
2025-03-030
2025-03-040
2025-03-050

UNION and UNION ALL

sql SELECT city AS place FROM customers WHERE city IS NOT NULL UNION SELECT category FROM products ORDER BY place;

Result:

place
Electronics
Furniture
London
Mumbai
Singapore
Stationery
Tel Aviv

UNION removes duplicates, which costs a sort. UNION ALL keeps everything and is faster. Choose UNION ALL unless you need distinct rows.

sql SELECT 'customer' AS kind, COUNT(*) AS n FROM customers UNION ALL SELECT 'product', COUNT(*) FROM products UNION ALL SELECT 'order', COUNT(*) FROM orders;

Result:

kindn
customer6
product8
order10

INTERSECT and EXCEPT (MySQL 8.0.31+)

sql SELECT customer_id FROM orders WHERE status = 'shipped' INTERSECT SELECT customer_id FROM orders WHERE status = 'pending' ORDER BY customer_id;

Result:

customer_id
1
3
sql SELECT id FROM customers EXCEPT SELECT customer_id FROM orders ORDER BY id;

Result:

id
4
Older MySQL Before 8.0.31 these two keywords are syntax errors. Use JOIN, IN or NOT EXISTS instead.

Common Beginner Mistakes

MistakeWhat happensFix
UNION when duplicates are fineSlowerUNION ALL
Different column counts in UNIONError 1222Match the columns
Recursive CTE with no stopError after 1000 levelsAdd a WHERE limit
Narrow anchor columnTruncated or failed valuesCAST to a wide type
Expecting a CTE to be a tableIt exists for one statement onlyUse a view or temp table

Practice

  1. Write a CTE for top-spending customers, then filter above average.
  2. Generate dates for a month with a recursive CTE.
  3. Print an org tree with indentation.
  4. Find customers who ordered but never received a delivered order using EXCEPT.

Conclusion

CTEs name subqueries, recursive CTEs walk trees and make series, UNION ALL combines results quickly, and INTERSECT/EXCEPT need MySQL 8.0.31+.

Quick Summary: WITH, recursive CTE, UNION, UNION ALL, INTERSECT, EXCEPT.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators