An Engineering team lead at Helix Systems wants a report showing every Engineering employee alongside their direct manager's name.
Write a query to return the employee name and manager name for every Engineering team member who has a manager on record.
Assumptions:
- The
employeestable contains every active and former employee at Helix Systems. - Engineering is identified by
department_id = 1. - The department condition applies to the employee role only, not to the manager role.
Output:
- One row per qualifying Engineering employee, with columns
employee_nameandmanager_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
FROM
employees e
JOIN employees m ON e.manager_id = m.id
WHERE
e.department_id = 1 The shape
The department filter applies to the employee role only, so the WHERE predicate names the employee alias (e.department_id = 1) and leaves the manager alias unconstrained. Managers can sit in any department; only the employee has to be in Engineering.
Clause by clause
SELECT e.name AS employee_name, m.name AS manager_namereturns the employee name and manager name from the two aliased instances ofemployees.FROM employees ereads the table in the employee role.JOIN employees m ON e.manager_id = m.idreads the table again in the manager role and pairs each employee with their manager. Anyone with nomanager_idis dropped at this step.WHERE e.department_id = 1restricts the employee role to Engineering. Marcus Reid (Engineering, managed by Sarah Chen from a different department) is in the result; Sarah Chen as a manager of Marcus is reachable throughmregardless of her own department.
Why this and not WHERE m.department_id = 1
The filter has to name the role it constrains. e.department_id = 1 keeps every Engineering employee paired with whoever their manager happens to be. m.department_id = 1 would do the opposite — keep every employee whose manager is in Engineering, regardless of the employee's own department. Same column on a different alias, different question. The prompt asks for Engineering employees, so the filter goes on e.
The trap
When both aliases share a column, the alias prefix on the WHERE filter is what scopes the result. Writing WHERE department_id = 1 without a prefix is a query error (the reference is ambiguous), but the more silent failure is writing the right column on the wrong alias and getting a plausible-looking result for the wrong question.
You practiced restricting one role of a self-join independently. Each alias can carry its own WHERE predicates — the employee condition and the manager condition stay separate.