Compare rows in the same table
Question
Find employees who earn more than their own manager. Show the employee's name, their salary, and the manager's name.
employeesid, name, salary, department_id, manager_id, hired_on
departmentsid, name, city
Your query
Ctrl+Enter to run
Result
Expected result
| name | salary | manager |
|---|---|---|
| Priya Nair | 9200 | Tom Becker |
| Lucas Moreau | 6800 | Ana Souza |
Hint
Self-join employees to employees on the manager id, then compare the two salaries.
Show the solution
solution.sql
Run this code
SELECT e.name, e.salary, m.name AS manager
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;
Why it works
After the self-join, each row holds an employee and their manager side by side, so a normal WHERE can compare them. Two people earn more than their manager: Priya Nair and Lucas Moreau.
Common mistake
Comparing e.salary > e.salary or forgetting which alias is which is easy here. Name the aliases after their role (e for employee, m for manager).