List Every Employee With Their Manager's Name (Self JOIN)

SQL coding challenge · Difficulty: easy · +50 XP

Problem

The org chart tool needs each employee displayed with their manager's name. Every employee appears — even the CEO who has no manager (show NULL).

Tables

Table: departments

| department_id | department_name |
| --- | --- |
| 1 | Engineering |
| 2 | Marketing |
| 3 | HR |
| 4 | Finance |

Table: employees

| employee_id | first_name | department_id | salary | hire_date | manager_id |
| --- | --- | --- | --- | --- | --- |
| 1 | Alice | 1 | 90000 | 2021-03-10 | NULL |
| 2 | Bob | 1 | 75000 | 2021-03-20 | 1 |
| 3 | Charlie | 1 | 80000 | 2021-03-25 | 1 |
| 4 | Victor | 1 | 65000 | 2022-01-15 | 1 |
| 5 | Diana | 2 | 70000 | 2022-06-05 | 1 |
| 6 | Eve | 2 | 65000 | 2021-11-15 | 5 |
| 7 | Frank | 3 | 60000 | 2023-02-28 | 1 |

Expected Output

| employee_id | first_name | manager_name |
| --- | --- | --- |
| 2 | Bob | Alice |
| 3 | Charlie | Alice |
| 4 | Victor | Alice |
| 5 | Diana | Alice |
| 6 | Eve | Diana |
| 7 | Frank | Alice |
  • Return: employee_id, first_name, manager_first_name
  • Employees with no manager → NULL
  • Sort by employee_id ascending
  • Hint: Join the employees table to itself: employees e LEFT JOIN employees m ON e.manager_id = m.employee_id

Solve this challenge on PySpark.in