Top earner per department, keeping ties
Task
For each department return the highest-paid employee. If two people tie for the top salary, return both. Columns: dept, name, salary.
Row order does not matter. Column names do not have to match. SQLite dialect.
Tables
employees
name TEXT, dept TEXT, salary INTEGER
| name | dept | salary |
|---|---|---|
| Asha | Data | 150 |
| Ben | Data | 150 |
| Chen | Data | 120 |
| Dev | Sales | 90 |
| Eli | Sales | 110 |
| Fay | Ops | 70 |
- Rank employees within each department (PARTITION BY dept).
- ROW_NUMBER picks one of the tied rows at random; RANK or DENSE_RANK gives both rank 1.
Expected output
| dept | name | salary |
|---|---|---|
| Data | Asha | 150 |
| Data | Ben | 150 |
| Ops | Fay | 70 |
| Sales | Eli | 110 |
Show solution
WITH ranked AS (
SELECT dept, name, salary,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk
FROM employees
)
SELECT dept, name, salary FROM ranked WHERE rnk = 1;ROW_NUMBER always breaks ties, so one of Asha and Ben would vanish, and which one can change between runs. RANK() = 1 keeps every tied row. A window function cannot go in WHERE, so rank in a CTE and filter outside.
Why this works
ROW_NUMBER always breaks ties, so one of Asha and Ben would vanish, and which one can change between runs. RANK() = 1 keeps every tied row. A window function cannot go in WHERE, so rank in a CTE and filter outside.
The full explanation, with more examples, is in the question Top earner per department, keeping ties.