IntermediateWindow functions

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

namedeptsalary
AshaData150
BenData150
ChenData120
DevSales90
EliSales110
FayOps70
Expected output
deptnamesalary
DataAsha150
DataBen150
OpsFay70
SalesEli110
Show solution
SQL
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.

The full explanation, with more examples, is in the question Top earner per department, keeping ties.