This is a great question about recursive CTEs (Common Table Expressions). I'll provide a comprehensive solution for building an organizational chart that shows the hierarchy from managers down to leaf employees with depth tracking.
Let me create a complete example that includes:
Sample data setup
A recursive CTE query
Explanation of how it works
Examples output
I'll use SQL Server syntax (which is standard for recursive CTEs), but mention that it's similar in PostgreSQL, MySQL 8.0+, and other databases.
Here's what I'll include:
CREATE TABLE statements for sample data
INSERT statements with sample employees and their managers
The recursive CTE query with proper explanation
A few variations showing different ways to use it
Output examples
Recursive CTE for Organizational Chart
Here's a comprehensive solution to build an organizational hierarchy with depth tracking:
-- Find organizational chart with depth tracking
WITH OrgChart AS (
-- Anchor member: Start with top-level employees (no manager)
SELECT
EmployeeID,
EmployeeName,
ManagerID,
Department,
Salary,
0 AS Level,
CAST(EmployeeName AS NVARCHAR(MAX)) AS HierarchyPath
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
-- Recursive member: Find all subordinates
SELECT
e.EmployeeID,
e.EmployeeName,
e.ManagerID,
e.Department,
e.Salary,
oc.Level + 1 AS Level,
CAST(oc.HierarchyPath + ' → ' + e.EmployeeName AS NVARCHAR(MAX))
AS HierarchyPath
FROM Employees e
INNER JOIN OrgChart oc ON e.ManagerID = oc.EmployeeID
)
SELECT *
FROM OrgChart
ORDER BY Level, HierarchyPath;
Output:
code
EmployeeID | EmployeeName | ManagerID | Department | Salary | Level | HierarchyPath
-----------|-------------------|-----------|--------------|---------|-------|------------------------------------------
1 | John Smith | NULL | Executive | 250000 | 0 | John Smith
2 | Sarah Johnson | 1 | Engineering | 180000 | 1 | John Smith → Sarah Johnson
3 | Michael Brown | 1 | Finance | 170000 | 1 | John Smith → Michael Brown
4 | Emily Davis | 2 | Engineering | 120000 | 2 | John Smith → Sarah Johnson → Emily Davis
5 | Robert Wilson | 2 | Engineering | 115000 | 2 | John Smith → Sarah Johnson → Robert Wilson
8 | Lisa Anderson | 3 | Finance | 105000 | 2 | John Smith → Michael Brown → Lisa Anderson
6 | Jennifer Lee | 4 | Engineering | 95000 | 3 | John Smith → Sarah Johnson → Emily Davis → Jennifer Lee
7 | David Martinez | 4 | Engineering | 92000 | 3 | John Smith → Sarah Johnson → Emily Davis → David Martinez
9 | James Taylor | 5 | Engineering | 85000 | 3 | John Smith → Sarah Johnson → Robert Wilson → James Taylor
10 | Patricia White | 8 | Finance | 75000 | 3 | John Smith → Michael Brown → Lisa Anderson → Patricia White
3. Advanced Version with Formatting
sql
-- Enhanced version with visual formatting and statistics
WITH OrgChart AS (
SELECT
EmployeeID,
EmployeeName,
ManagerID,
Department,
Salary,
0 AS Level,
CAST(EmployeeName AS NVARCHAR(MAX)) AS HierarchyPath,
1 AS DirectReports
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT
e.EmployeeID,
e.EmployeeName,
e.ManagerID,
e.Department,
e.Salary,
oc.Level + 1,
oc.HierarchyPath + ' → ' + e.EmployeeName,
1
FROM Employees e
INNER JOIN OrgChart oc ON e.ManagerID = oc.EmployeeID
)
SELECT
REPLICATE(' ', Level) + '├─ ' AS [Indent],
EmployeeName,
ManagerID,
Department,
Salary,
Level,
HierarchyPath
FROM OrgChart
ORDER BY HierarchyPath;
4. Find Specific Hierarchy (Top-Down from a Manager)
sql
-- Get all subordinates for a specific manager
DECLARE @ManagerName NVARCHAR(100) = 'Sarah Johnson';
WITH OrgChart AS (
SELECT
EmployeeID,
EmployeeName,
ManagerID,
Department,
Salary,
0 AS Level,
CAST(EmployeeName AS NVARCHAR(MAX)) AS HierarchyPath
FROM Employees
WHERE EmployeeName = @ManagerName
UNION ALL
SELECT
e.EmployeeID,
e.EmployeeName,
e.ManagerID,
e.Department,
e.Salary,
oc.Level + 1,
oc.HierarchyPath + ' → ' + e.EmployeeName
FROM Employees e
INNER JOIN OrgChart oc ON e.ManagerID = oc.EmployeeID
)
SELECT *
FROM OrgChart
ORDER BY Level;
5. Find Upward Hierarchy (Employee to CEO)
sql
-- Get manager chain from a specific employee up to CEO
DECLARE @EmployeeID INT = 9; -- James Taylor
WITH ManagerChain AS (
SELECT
EmployeeID,
EmployeeName,
ManagerID,
Department,
0 AS Level,
CAST(EmployeeName AS NVARCHAR(MAX)) AS ChainPath
FROM Employees
WHERE EmployeeID = @EmployeeID
UNION ALL
SELECT
m.EmployeeID,
m.EmployeeName,
m.ManagerID,
m.Department,
mc.Level + 1,
m.EmployeeName + ' → ' + mc.ChainPath
FROM Employees m
INNER JOIN ManagerChain mc ON m.EmployeeID = mc.ManagerID
)
SELECT *
FROM ManagerChain
ORDER BY Level DESC;
Output:
code
EmployeeID | EmployeeName | ManagerID | Department | Level | ChainPath
-----------|----------------|-----------|--------------|-------|----------------------------------------
1 | John Smith | NULL | Executive | 3 | John Smith → Sarah Johnson → Robert Wilson → James Taylor
2 | Sarah Johnson | 1 | Engineering | 2 | Sarah Johnson → Robert Wilson → James Taylor
5 | Robert Wilson | 2 | Engineering | 1 | Robert Wilson → James Taylor
9 | James Taylor | 5 | Engineering | 0 | James Taylor
6. Count Subordinates at Each Level
sql
-- Count total and direct subordinates
WITH OrgChart AS (
SELECT
EmployeeID,
EmployeeName,
ManagerID,
0 AS Level,
CAST(EmployeeID AS NVARCHAR(MAX)) AS ParentPath
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT
e.EmployeeID,
e.EmployeeName,
e.ManagerID,
oc.Level + 1,
oc.ParentPath + ',' + CAST(e.EmployeeID AS NVARCHAR(MAX))
FROM Employees e
INNER JOIN OrgChart oc ON e.ManagerID = oc.EmployeeID
),
SubordinateCounts AS (
SELECT
oc.EmployeeID,
oc.EmployeeName,
oc.Level,
COUNT(DISTINCT e.EmployeeID) - 1 AS TotalSubordinates,
(SELECT COUNT(*) FROM Employees WHERE ManagerID = oc.EmployeeID)
AS DirectReports
FROM OrgChart oc
LEFT JOIN OrgChart e ON e.ParentPath LIKE '%' + CAST(oc.EmployeeID AS VARCHAR(MAX)) + '%'
GROUP BY oc.EmployeeID, oc.EmployeeName, oc.Level
)
SELECT *
FROM SubordinateCounts
ORDER BY Level, EmployeeName;
7. Visualization with Tree Format
sql
-- Create a tree-like visual representation
WITH OrgChart AS (
SELECT
EmployeeID,
EmployeeName,
ManagerID,
Department,
Salary,
0 AS Level,
CAST('/' + EmployeeName + '/' AS NVARCHAR(MAX)) AS SortPath,
CAST(EmployeeName AS NVARCHAR(MAX)) AS HierarchyPath,
0 AS IsLeaf
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
SELECT
e.EmployeeID,
e.EmployeeName,
e.ManagerID,
e.Department,
e.Salary,
oc.Level + 1,
oc.SortPath + e.EmployeeName + '/',
oc.HierarchyPath + ' → ' + e.EmployeeName,
(SELECT COUNT(*) FROM Employees WHERE ManagerID = e.EmployeeID)
FROM Employees e
INNER JOIN OrgChart oc ON e.ManagerID = oc.EmployeeID
)
SELECT
EmployeeID,
REPLICATE(' ', Level) +
CASE WHEN IsLeaf = 0 THEN '├─' ELSE '└─' END + ' ' AS TreeNode,
EmployeeName,
Department,
Salary,
Level,
CASE WHEN IsLeaf = 0 THEN 'Manager' ELSE 'Employee' END AS Position
FROM OrgChart
ORDER BY SortPath;
Key Concepts Explained
Concept
Explanation
Anchor Member
Initial query defining root nodes (ManagerID IS NULL)
Recursive Member
Joins to find all child rows for each parent
UNION ALL
Combines anchor and recursive results
Termination
Recursion stops when no more rows match the JOIN condition
MAX RECURSION DEPTH
SQL Server default is 100 (adjustable with OPTION)
Performance Considerations
sql
-- Add index for better performance
CREATE INDEX IX_Employees_ManagerID
ON Employees(ManagerID)
INCLUDE (EmployeeID, EmployeeName, Salary);
-- Specify max recursion level to prevent runaway queries
WITH OrgChart AS (
-- ... CTE definition ...
)
SELECT * FROM OrgChart
OPTION (MAXRECURSION 10); -- Limit recursion depth
This comprehensive guide covers most common organizational hierarchy scenarios using recursive CTEs!