Hard Subqueries and CTEs Employees database

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

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

Expected result

namedepartment_idsalary
Priya Nair19200
Lucas Moreau26800
Sofia Rossi36100
Aisha Bello44700

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

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.

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