List Employees with Their Manager Names Using a Self Join
Return each employee's first name next to the first name of their manager.
The challenge runs on the SQLabHub practice database (SQLite) and uses the employees table. You can solve it in the browser, with nothing to install.
The task
Show employees with their manager name.
A correct answer returns 120 rows with 2 columns: first_name, manager.
Tables used in this challenge
employees 120 rows
id INTEGER (PK) · first_name TEXT · last_name TEXT · email TEXT · department TEXT · department_id INTEGER · title TEXT · salary REAL · hire_date TEXT · manager_id INTEGER · city TEXT · status TEXT
| id | first_name | last_name | department | department_id | title | salary | hire_date | manager_id | city | status | |
|---|---|---|---|---|---|---|---|---|---|---|---|
The first rows of each table are shown. See how all the tables relate on the database schema page.
Expected output
| first_name | manager |
|---|---|
First 5 of 120 rows. This is the output of the model solution on the practice database. The task does not fix a sort order, so your rows may come back in a different order.
What you practise
- Choosing exactly which columns a query returns
- Keeping every row of the left table with LEFT JOIN, matched or not
- Joining a table to itself under two aliases
Hint and approach
Try the challenge first. Open these only when you need them.
Show the hint
Self JOIN
Show the step-by-step approach
How the model solution is built, in the order the database evaluates it:
- Read from the
employeestable, under the aliase. - LEFT JOIN
employeesagain, under the aliasm, one.manager_id=m.id. Rows from the left side that have no match are kept, with NULL in the joined columns. - Return only the columns
e.first_nameandm.first_name.
Model solution
Checking your session…
What to watch for
The employees table is joined to itself under two aliases, one playing the employee and one the manager. A LEFT JOIN keeps the ten people at the top who have no manager; an inner join would drop them.
- Self join. Without a condition such as a.id < b.id, a self join pairs every row with itself and lists each pair twice.
- LEFT JOIN. A WHERE condition on the right-hand table removes the unmatched rows and turns the LEFT JOIN back into an inner join. Conditions on that table go in the ON clause.
Related SQL challenges
- Find Pairs of Employees in the Same DepartmentSimilar levelMedium
- Sort Employees by Department, Then by SalarySimilar levelMedium
- Compare Each Employee's Salary with Their Manager'sHarderHard
- Count Orders and Total Spend for Every User, Including ZeroSimilar levelMedium
- Find Managers Who Earn More Than All Their Direct ReportsHarderHard
Keep learning
- Lesson: SELF JOIN
- Lesson: LEFT JOIN
- Lesson: The BIG 6 SQL Clauses
- All SQL practice challenges, by difficulty and topic
- SQL interview questions with answers
- SQL Playground: run any query on the same database