Highest paid employee in each department
Question
For each department, show the name, department_id and salary of the employee with the highest salary.
employeesid, name, salary, department_id, manager_id, hired_on
departmentsid, name, city
Your query
Ctrl+Enter to run
Result
Expected result
| name | department_id | salary |
|---|---|---|
| Priya Nair | 1 | 9200 |
| Lucas Moreau | 2 | 6800 |
| Sofia Rossi | 3 | 6100 |
| Aisha Bello | 4 | 4700 |
Hint
A correlated subquery can find the maximum salary of the current row's department.
Show the solution
solution.sql
Run this code
SELECT e.name, e.department_id, e.salary
FROM employees e
WHERE e.salary = (
SELECT MAX(salary)
FROM employees
WHERE department_id = e.department_id
);
Why it works
The subquery uses e.department_id from the outer row, so it is run once per employee and returns the top salary of that employee's department. Only the employees who match it are kept.
Common mistake
GROUP BY department_id with MAX(salary) gives the top salaries but not reliably the right names. To get the whole row of the top earner, compare against the maximum like this, or use a window function.