Department Top Salary

Medium SQLWindowJOIN

Problem

Schemas: Employee(id INT, name VARCHAR, salary INT, dept_id INT), Department(id INT, name VARCHAR). For each department, return the department name and the names of every employee whose salary is the top in that department (ties included).

Example 1 Input: IT: Ada 90, Bo 90, Cy 80 Output: (IT, Ada), (IT, Bo)

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

SQL

SELECT d.name AS department, e.name AS employee
FROM Employee e
JOIN Department d ON d.id = e.dept_id
WHERE (e.dept_id, e.salary) IN (
  SELECT dept_id, MAX(salary)
  FROM Employee
  GROUP BY dept_id
);

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Department Top Salary interactively → ← All solutions