Keep unmatched rows with LEFT JOIN
Question
List every employee's name with the name of their manager. Employees without a manager must still appear, with an empty (NULL) manager.
employeesid, name, salary, department_id, manager_id, hired_on
departmentsid, name, city
Your query
Ctrl+Enter to run
Result
Expected result
| employee | manager |
|---|---|
| Tom Becker | NULL |
| Ana Souza | NULL |
| Priya Nair | Tom Becker |
| Lucas Moreau | Ana Souza |
| Mei Chen | Tom Becker |
| Omar Haddad | Ana Souza |
| Sofia Rossi | NULL |
| Jonas Berg | Sofia Rossi |
| Aisha Bello | NULL |
| Diego Ruiz | Aisha Bello |
| Hana Kim | Tom Becker |
| Liam Walsh | Aisha Bello |
Hint
A LEFT JOIN keeps every row of the left table, even when nothing matches on the right. You can join a table to itself.
Show the solution
solution.sql
Run this code
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;
Why it works
The table is joined to itself, once as the employee (e) and once as the manager (m). With LEFT JOIN, the four people who have no manager stay in the result, with NULL in the manager column.
Common mistake
With a plain JOIN the employees without a manager disappear, because there is no matching row for them. That is the difference between INNER and LEFT JOIN.