Highest salary in each department
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
| id | name |
|---|---|
| 1 | Engineering |
| 2 | Sales |
employees
| id | name | salary | department_id |
|---|---|---|---|
| 1 | Noa | 90000 | 1 |
| 2 | Avi | 70000 | 2 |
| 3 | Dana | 85000 | 1 |
| 4 | Yossi | 90000 | 1 |
| 5 | Maya | 65000 | 2 |
Result:
| department | employee | salary |
|---|---|---|
| Engineering | Noa | 90000 |
| Engineering | Yossi | 90000 |
| Sales | Avi | 70000 |
Tip
GROUP BY department_id gives you the top salary, but not who earns it. How do you get back to the employee?
Schema
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:
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:
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
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;