A Simple CTE
A Common Table Expression gives a subquery a name so the main query reads top to bottom:
Result:
| name | total |
|---|---|
| Asha Rao | 1349.00 |
| Eli Brown | 989.00 |
| Chen Wei | 706.00 |
| Fatima Khan | 678.00 |
| Ben Carter | 659.00 |
Several CTEs
Result:
| name | order_id | items |
|---|---|---|
| Asha Rao | 1 | 3 |
| Asha Rao | 2 | 14 |
| Chen Wei | 4 | 3 |
| Eli Brown | 6 | 3 |
| Asha Rao | 7 | 3 |
| Chen Wei | 8 | 21 |
| Ben Carter | 10 | 12 |
Recursive CTE: Number Series
Result:
| i | square |
|---|---|
| 1 | 1 |
| 2 | 4 |
| 3 | 9 |
| 4 | 16 |
| 5 | 25 |
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:
ERROR 3636: Recursive query aborted after 1001 iterations. Try increasing @@cte_max_recursion_depth to a larger value.
Recursive CTE: Org Chart
Result:
| org | path |
|---|---|
| Zara | Zara |
| Xin | Zara > Xin |
| Yusuf | Zara > Yusuf |
| Wale | Zara > Yusuf > Wale |
| Vik | Zara > Yusuf > Wale > Vik |
CAST(name AS CHAR(200)) a long path would be cut or fail in strict mode.
Recursive CTE: Fill Date Gaps
Result:
| d | orders |
|---|---|
| 2025-03-01 | 1 |
| 2025-03-02 | 0 |
| 2025-03-03 | 0 |
| 2025-03-04 | 0 |
| 2025-03-05 | 0 |
UNION and UNION ALL
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.
Result:
| kind | n |
|---|---|
| customer | 6 |
| product | 8 |
| order | 10 |
INTERSECT and EXCEPT (MySQL 8.0.31+)
Result:
| customer_id |
|---|
| 1 |
| 3 |
Result:
| id |
|---|
| 4 |
JOIN, IN or NOT EXISTS instead.
Common Beginner Mistakes
| Mistake | What happens | Fix |
|---|---|---|
UNION when duplicates are fine | Slower | UNION ALL |
Different column counts in UNION | Error 1222 | Match the columns |
| Recursive CTE with no stop | Error after 1000 levels | Add a WHERE limit |
| Narrow anchor column | Truncated or failed values | CAST to a wide type |
| Expecting a CTE to be a table | It exists for one statement only | Use a view or temp table |
Practice
- Write a CTE for top-spending customers, then filter above average.
- Generate dates for a month with a recursive CTE.
- Print an org tree with indentation.
- 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+.

