SQL Recursive CTE for Hierarchy Traversal

Day 39/90 — SQL Series | Week 6: CTEs A regular CTE queries flat data. A recursive CTE traverses an entire tree — level by level. Here is the only SQL-native way to walk a parent-child hierarchy: Step 1 → start at the root (CEO has no manager) Step 2 → find everyone who reports to the root Step 3 → find everyone who reports to THEM Step 4 → keep going until no new rows are found Each pass goes one level deeper — like peeling an onion layer by layer. WITH RECURSIVE org_tree AS ( SELECT emp_id, emp_name, manager_id, 1 AS level FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.emp_id, e.emp_name, e.manager_id, t.level + 1 FROM employees e JOIN org_tree t ON e.manager_id = t.emp_id ) SELECT * FROM org_tree ORDER BY level; The 2 parts you must know: → Anchor member — runs once, returns the root rows → Recursive member — joins the CTE to itself, runs until no new rows found This pattern works for any hierarchy — org charts, folder trees, product categories. One query. Any depth. No loops. No external tools. Save this. Try writing both parts from memory. #SQL #RecursiveCTE #DataAnalytics #LearnSQL #DataAnalyst #SQL90Days

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories