Skip to main content
05

Highest salary in each department

Mediumwindow functionsRANKJOIN

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

Write a query that returns the highest paid employee in each department. Return the columns department (the department name), employee and salary.

If several employees share the top salary of their department, return all of them. Departments with no employees don't appear. Rows can be returned in any order.

Example

departments

idname
1Engineering
2Sales

employees

idnamesalarydepartment_id
1Noa900001
2Avi700002
3Dana850001
4Yossi900001
5Maya650002

Result:

departmentemployeesalary
EngineeringNoa90000
EngineeringYossi90000
SalesAvi70000

Tip

GROUP BY department_id gives you the top salary, but not who earns it. How do you get back to the employee?

Schema

sql
CREATE TABLE departments (
  id   INT PRIMARY KEY,
  name TEXT NOT NULL
);

CREATE TABLE employees (
  id            INT PRIMARY KEY,
  name          TEXT NOT NULL,
  salary        INT NOT NULL,
  department_id INT NOT NULL REFERENCES departments (id)
);

Approach

A window function ranks the employees inside each department without collapsing the rows the way GROUP BY does:

sql
SELECT department, employee, salary
FROM (
  SELECT
    d.name AS department,
    e.name AS employee,
    e.salary,
    RANK() OVER (PARTITION BY e.department_id ORDER BY e.salary DESC) AS rnk
  FROM employees e
  JOIN departments d ON d.id = e.department_id
) ranked
WHERE rnk = 1;

PARTITION BY restarts the ranking for every department. RANK gives tied salaries the same rank, so both 90000 earners get 1. ROW_NUMBER would pick one of them at random, which is the classic bug here.

You can't filter on rnk in the same SELECT's WHERE: window functions run after WHERE. That is why the query wraps them in a subquery (a CTE works too).

Without window functions

Compute each department's maximum, then join back to find who earns it:

sql
SELECT d.name AS department, e.name AS employee, e.salary
FROM employees e
JOIN departments d ON d.id = e.department_id
JOIN (
  SELECT department_id, MAX(salary) AS top
  FROM employees
  GROUP BY department_id
) m ON m.department_id = e.department_id AND m.top = e.salary;

It keeps ties too. Window functions scale better to "top N", which comes up later in this list.

Postgres bonus: DISTINCT ON

If the interviewer says "one employee per department, any of the tied ones", Postgres has a shortcut: SELECT DISTINCT ON (department_id) ... ORDER BY department_id, salary DESC.

Reference solution

sql
SELECT department, employee, salary
FROM (
  SELECT
    d.name AS department,
    e.name AS employee,
    e.salary,
    RANK() OVER (PARTITION BY e.department_id ORDER BY e.salary DESC) AS rnk
  FROM employees e
  JOIN departments d ON d.id = e.department_id
) ranked
WHERE rnk = 1;