Recursive Queries — Complete Guide
Recursive Queries — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MySQL Tutorial on Toolliyo Academy.
On this page
MySQL Tutorial · Lesson 72 of 100
Recursive Queries
Basics ✓ → Advanced
Advanced · 2 — Production · ~10 min · MySQL — Advanced MySQL
What is this?
Recursive CTEs walk hierarchies: org chart, category tree, bill of materials. Anchor member seeds base rows; recursive member joins until no new rows.
Why should you care?
Show all subcategories under “Electronics” on DataFlow catalog menu — recursion expands tree in one SQL call.
See it live — copy this example
Run in MySQL Workbench or the mysql CLI.
WITH RECURSIVE cat_tree AS (
SELECT category_id, name, parent_id, 0 AS depth
FROM categories WHERE category_id = 1
UNION ALL
SELECT c.category_id, c.name, c.parent_id, ct.depth + 1
FROM categories c
JOIN cat_tree ct ON c.parent_id = ct.category_id
)
SELECT * FROM cat_tree ORDER BY depth, name;
What happened?
- Anchor picks root category 1.
- Recursive part attaches children whose parent_id matches row already in cat_tree.
- depth tracks level; stops when no new children.
Practice next
- CREATE categories with parent_id self-FK.
- Insert 3-level tree.
- Run recursive CTE from root id 1.
- Start from leaf upward using different join direction.
- cte_max_recursion_depth system variable if deep tree.
Remember
UNION ALL links anchor + recursive parts. Great for trees and graphs with parent pointers. Guard depth or cycle detection in data.
DataFlow category breadcrumb
API builds breadcrumb trail from recursive CTE to root for SEO URLs.
Outcome: Single query replaces recursive app code.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!