Traverse a hierarchy with a recursive CTEΒΆ
Create a small employee tree, then walk down from the root with a depth guard. The guard makes the example terminate even if a later data change introduces a cycle.
CREATE DATABASE cookbook_hierarchy;
CREATE TABLE cookbook_hierarchy.staff(id INT PRIMARY KEY, name VARCHAR(30), manager_id INT);
INSERT INTO cookbook_hierarchy.staff VALUES
(1,'Alice',NULL),(2,'Bob',1),(3,'Charlie',1),(4,'David',2);
WITH RECURSIVE tree AS (
SELECT id,name,manager_id,0 AS depth FROM cookbook_hierarchy.staff WHERE id=1
UNION ALL
SELECT s.id,s.name,s.manager_id,t.depth+1
FROM cookbook_hierarchy.staff s JOIN tree t ON s.manager_id=t.id
WHERE t.depth<3
)
SELECT name,depth FROM tree ORDER BY depth,name;
DROP DATABASE cookbook_hierarchy;
Expect Alice at depth 0, Bob and Charlie at depth 1, and David at depth 2. For a real graph, also track visited IDs so a cycle cannot repeat rows until the depth limit. See the v4.1.0 source test.