chaturIQ
Thinking habit: Know which way the arrow points

SQL self join: employees who earn more than their manager

The question: List the employees who earn more than their own manager.

employees

emp_idnamesalarymanager_id
1Asha150000NULL
2Ravi900001
3Neha1600001
4Kabir950002
5Meera600002
6Arjun990003

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.

Open the lesson

More SQL interview questions