Medium SQL joins practice Employees database

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

Press Run to see your query's result, or Check answer to compare it with the expected result.

Expected result

namesalarymanager
Priya Nair9200Tom Becker
Lucas Moreau6800Ana Souza

Rows can come in any order. Column names do not have to match.

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).

Want to try the query on MySQL or PostgreSQL? Open it in the SQL Online Compiler or SQLite Online.