Write a recursive CTE to find an organizational chart. Trace hierarchy from a manager…
- User
Write a recursive CTE to find an organizational chart. Trace hierarchy from a manager down to all leaf employees tracking the level depth.
- Assistant
Writing recursive SQL CTE for org chart
A recursive CTE anchors on a manager then recursively joins employees reporting to them, incrementing a depth level. Optionally filtering leaf employees (those without subordinates) uses a NOT EXISTS subquery. This solution works in SQL Server, Postgres, and similar databases supporting recursive queries. Given a simple self–referencing
employeestableCREATE TABLE employees ( emp_id INT PRIMARY KEY, emp_name VARCHAR(100), manager_id INT REFERENCES employees(emp_id) );you can walk the tree starting at a particular manager with a recursive common table expression. The anchor member seeds the CTE with the starting manager, the recursive member joins employees to the rows already found and increments the level:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.