Write a query to list all employees and their managers by employee ID.
Instruction: Assuming a table 'employees' with columns 'employee_id', 'name', and 'manager_id', write a SQL query to list each employee with their direct manager.
Updated
Official answer
Assume employee_id uniquely identifies each employee. A self left join returns every employee and their direct manager:
SELECT e.employee_id, e.name AS employee_name,
m.employee_id AS manager_id, m.name AS manager_name
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
ORDER BY e.employee_id;
An employee with no manager has NULL manager fields. If an unenforced manager_id points to a missing row, the joined fields are also NULL; select e.manager_id separately when diagnosing that distinction. A foreign key can prevent invalid references but does not prevent longer reporting cycles.
The two aliases represent different roles of the same table. An inner join would omit employees without a matching manager. This query returns only the direct manager; traversing all ancestors requires a recursive query with cycle handling. Test a root, a normal report and an empty table, and preserve the unique employee key to avoid multiplying matches.