SQL self join: employees who earn more than their manager
The question: List the employees who earn more than their own manager.
employees
| emp_id | name | salary | manager_id |
|---|---|---|---|
| 1 | Asha | 150000 | NULL |
| 2 | Ravi | 90000 | 1 |
| 3 | Neha | 160000 | 1 |
| 4 | Kabir | 95000 | 2 |
| 5 | Meera | 60000 | 2 |
| 6 | Arjun | 99000 | 3 |
This query looks right. Run it, decide if it is, and fix it.
SELECT e.name FROM employees e JOIN employees m ON e.emp_id = m.manager_id WHERE e.salary > m.salary;
Show the answer and why the first query is wrong
Why the usual answer is wrong
SELECT e.name FROM employees e JOIN employees m ON e.emp_id = m.manager_id WHERE e.salary > m.salary;
The join is the wrong way round: it pairs each person with the people who report to them, so it lists managers who earn more than someone in their team (Asha, Ravi, Neha).
The answer
SELECT e.name FROM employees e JOIN employees m ON e.manager_id = m.emp_id WHERE e.salary > m.salary;
Give the table two names: e for the employee, m for the manager. Each employee row points to its manager through manager_id, so the join is e.manager_id = m.emp_id.
Say it out loud before you write it: "for each employee, find their manager". The ON clause then writes itself. Asha has no manager, so the join drops her, which is what we want here.
Practise more like this, on real business data
324 interview-style questions on 35 tables with the duplicates, NULLs and missing weeks interviewers test. Free.