Medium SQL joins practice Employees database

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

Press Run to see your query's result, or Check answer to compare it with the expected result.

Expected result

employeemanager
Tom BeckerNULL
Ana SouzaNULL
Priya NairTom Becker
Lucas MoreauAna Souza
Mei ChenTom Becker
Omar HaddadAna Souza
Sofia RossiNULL
Jonas BergSofia Rossi
Aisha BelloNULL
Diego RuizAisha Bello
Hana KimTom Becker
Liam WalshAisha Bello

Rows can come in any order. Column names do not have to match.

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.

Want to try the query on MySQL or PostgreSQL? Open it in the SQL Online Compiler or SQLite Online.