Top Earner Per Department
Return the highest-paid employee in every department. Where two employees in the same department are tied on salary, return both.
Order the result by department name, then by employee name.
Expected output
department | employee | salary
------------+----------+----------
Engineering | Alice | 120000.00
Sales | Carol | 91000.25
Sales | Dan | 91000.25
Support | Erin | 64000.00
Editorial
The shape to reach for is "rows that match an aggregate over their own group", and there are two idiomatic ways to write it in PostgreSQL.
The correlated subquery states the condition directly — keep a row when its salary equals the maximum salary within its own department:
SELECT d.name AS department, e.name AS employee, e.salary
FROM employee e
JOIN department d ON d.id = e.department_id
WHERE e.salary = (
SELECT max(s.salary) FROM employee s WHERE s.department_id = e.department_id
)
ORDER BY d.name, e.name;
The window-function form computes the ranking once rather than re-running an aggregate per row, which is the version that scales:
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 r
FROM employee e
JOIN department d ON d.id = e.department_id
) ranked
WHERE r = 1
ORDER BY department, employee;
The trap is ROW_NUMBER() instead of RANK().
Both number rows within a partition, but ROW_NUMBER breaks ties
arbitrarily and so returns exactly one row per department — dropping Dan. The
two are interchangeable only when the ordering key is unique, and a salary
column almost never is. This is the most common wrong answer to this problem,
and the interviewer's follow-up is usually "what happens on a tie?"
Note also that the window function cannot go in the WHERE clause
directly: window functions are evaluated after WHERE, which is why
the ranking needs a subquery or a CTE around it.
Complexity
The correlated subquery is O(n) aggregate evaluations in the
worst case, one per candidate row, though a planner will often turn it into a
hash aggregate plus a join. The window form sorts once per partition, so it is
O(n log n) overall and has a flatter plan to read. On five seeded
rows neither matters; on a million-row table the difference is the whole
answer, and EXPLAIN ANALYZE on both is worth the two minutes.
department
3 rows
| idinteger | nametext |
|---|---|
| 1 | Engineering |
| 2 | Sales |
| 3 | Support |
employee
5 rows
| idinteger | nametext | salarynumeric(10,2) | department_idinteger |
|---|---|---|---|
| 1 | Alice | 120000 | 1 |
| 2 | Bob | 95000.5 | 1 |
| 3 | Carol | 91000.25 | 2 |
| 4 | Dan | 91000.25 | 2 |
| 5 | Erin | 64000 | 3 |