Helix Systems' HR reporting team needs a table showing each employee's name, their manager's name, and the department the employee belongs to.
Write a query to return all three values for every employee with a manager on record.
Assumptions:
- The
employeestable contains every active and former employee at Helix Systems. - The
departmentstable contains every department; each employee'sdepartment_idpoints to a row indepartments. - The query brings together two relationships: each employee paired with their manager (both from
employees), and each employee paired with their department.
Output:
- One row per employee with a manager, with columns
employee_name,manager_name, anddepartment_name.
Schema · hr 4 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
e.name AS employee_name,
m.name AS manager_name,
d.name AS department_name
FROM
employees e
JOIN employees m ON e.manager_id = m.id
JOIN departments d ON e.department_id = d.id The shape
Three aliases name three roles in the query: e is the employee, m is the manager (also from employees), and d is the department from departments. The self-join supplies the manager name; a second, ordinary join supplies the department name.
Clause by clause
SELECT e.name AS employee_name, m.name AS manager_name, d.name AS department_namepullsnamefrom each of the three aliases. Three different roles, three labeled columns.FROM employees ereadsemployeesin the employee role.JOIN employees m ON e.manager_id = m.idreadsemployeesagain in the manager role. This is the self-join; both sides reference the same physical table, distinguished only by the aliases.JOIN departments d ON e.department_id = d.idreadsdepartmentsand links each employee to their department. The join is on the employee'sdepartment_id, not the manager's — the prompt asks for the department the employee belongs to.
Why this and not JOIN departments d ON m.department_id = d.id
Which alias the department join keys to decides whose department appears in the result. e.department_id = d.id pairs each row with the employee's department (Marcus Reid → Engineering). m.department_id = d.id would pair each row with the manager's department instead (Marcus Reid → whatever department Sarah Chen sits in). The prompt asks for the employee's department, so the join keys to e.
The trap
Once two aliases share a foreign key column (department_id), every downstream join has to commit to one of them. The query parses either way and returns the same column count and similar row count, so the mistake doesn't surface as an error. Trace which role the prompt is asking about before writing the second join's ON clause.
You practiced combining a self-join with a regular join. Aliases keep the roles distinct — e, m, and d each name a different participant, even when two of them come from the same table.