Self Join Hierarchy Employee Manager

Query an employee manager hierarchy using a self join with multiple levels to flatten the organizational structure.

SqlData Fetching

Code

sqlsnippet
9 lines
SELECT
  e.employee_id,
  e.employee_name,
  m1.employee_name AS manager_name,
  m2.employee_name AS grandmanager_name
FROM employees e
LEFT JOIN employees m1 ON e.manager_id = m1.employee_id
LEFT JOIN employees m2 ON m1.manager_id = m2.employee_id
ORDER BY e.employee_id;

Inside the snippet

At its core this is a single SELECT statement against employees.

Mechanically, the statements are built from: 2 JOINs combining rows across tables; an ORDER BY that fixes the output order.

What to watch for

  • 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.

Using it

The employees table is the working surface here.

Key statements

SELECT
e.employee_id,
e.employee_name,
m1.employee_name AS manager_name,
m2.employee_name AS grandmanager_name
FROM employees e
LEFT JOIN employees m1 ON e.manager_id = m1.employee_id
LEFT JOIN employees m2 ON m1.manager_id = m2.employee_id
ORDER BY e.employee_id;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`employees`, combined through 2 joins.