InterviewPrepKit

Home / SQL / Joins

Self Join: Employees and Their Managers

medium
Solving tips
  • A self join lists the same table twice with different aliases so each row can reference another row in the table.
  • Match the child's manager_id to the parent's id; use a LEFT JOIN so the top boss (manager_id NULL) is not dropped.
  • Alias every column you output to avoid ambiguity, since both aliases expose a name column.

Each employee reports to another employee via manager_id. Show every employee next to the name of their manager.

Schema

CREATE TABLE employees (
    id         INT PRIMARY KEY,
    name       VARCHAR(50) NOT NULL,
    manager_id INT REFERENCES employees(id)
);

employees

idnamemanager_id
1AliceNULL
2Bob1
3Carol1
4Dave2
5Eve2

Task

Return one row per employee with columns employee_name and manager_name. Include employees who have no manager, showing manager_name as NULL for them. Order by employee_name ascending.

Expected output

employee_namemanager_name
AliceNULL
BobAlice
CarolAlice
DaveBob
EveBob
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.