Introduction
Recursive CTEs help us find and show data that is connected in a chain, like family trees or company departments.
WITH RECURSIVE cte_name (column_list) AS ( -- Anchor member: select the starting rows SELECT columns FROM table WHERE condition UNION ALL -- Recursive member: select rows that connect to previous rows SELECT columns FROM table JOIN cte_name ON join_condition ) SELECT * FROM cte_name;
WITH RECURSIVE EmployeeHierarchy (EmployeeID, ManagerID, Level) AS ( SELECT EmployeeID, ManagerID, 1 FROM Employees WHERE ManagerID IS NULL UNION ALL SELECT e.EmployeeID, e.ManagerID, eh.Level + 1 FROM Employees e JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID ) SELECT * FROM EmployeeHierarchy;
WITH RECURSIVE FolderTree (FolderID, ParentFolderID, Path) AS ( SELECT FolderID, ParentFolderID, CAST(FolderName AS VARCHAR(100)) FROM Folders WHERE ParentFolderID IS NULL UNION ALL SELECT f.FolderID, f.ParentFolderID, CONCAT(ft.Path, '/', f.FolderName) FROM Folders f JOIN FolderTree ft ON f.ParentFolderID = ft.FolderID ) SELECT * FROM FolderTree;
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, EmployeeName VARCHAR(50), ManagerID INT ); INSERT INTO Employees (EmployeeID, EmployeeName, ManagerID) VALUES (1, 'Alice', NULL), (2, 'Bob', 1), (3, 'Charlie', 1), (4, 'David', 2), (5, 'Eva', 2), (6, 'Frank', 3); WITH RECURSIVE EmployeeHierarchy (EmployeeID, EmployeeName, ManagerID, Level) AS ( SELECT EmployeeID, EmployeeName, ManagerID, 1 FROM Employees WHERE ManagerID IS NULL UNION ALL SELECT e.EmployeeID, e.EmployeeName, e.ManagerID, eh.Level + 1 FROM Employees e JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID ) SELECT EmployeeID, EmployeeName, ManagerID, Level FROM EmployeeHierarchy ORDER BY Level, EmployeeID;
RECURSIVE CTE in SQL when working with hierarchical data?OrgChart in SQL?WITH RECURSIVE Name AS ( ... ).Employees(id, name, manager_id) where manager_id references id, what will the following query return?WITH RECURSIVE Subordinates AS ( SELECT id, name, manager_id FROM Employees WHERE id = 2 UNION ALL SELECT e.id, e.name, e.manager_id FROM Employees e JOIN Subordinates s ON e.manager_id = s.id ) SELECT * FROM Subordinates;
WITH RECURSIVE Descendants AS ( SELECT id, parent_id FROM Tree WHERE id = 1 UNION ALL SELECT t.id, t.parent_id FROM Tree t JOIN Descendants d ON t.id = d.parent_id ) SELECT * FROM Descendants;
parent_id points to its parent. To find descendants, join where child's parent_id equals parent's id.t.id = d.parent_id. It should be t.parent_id = d.id to find children of current nodes.Parts(id, name, parent_part_id) representing assemblies and subassemblies. Write a recursive CTE query to find the full hierarchy of parts under part with id = 10, including the root part itself, and show the level (depth) of each part in the hierarchy starting at 0 for the root. Which query is correct?parent_part_id matches current part's id, and increments level by 1 to track depth.Pass the test and this pattern moves unknown