InterviewPrepKit

Home / SQL / Window Functions

Top 2 Earners per Department

hard
Solving tips
  • Top-N-per-group is ROW_NUMBER() OVER (PARTITION BY group ORDER BY metric DESC) in a CTE, then filter the number <= N in the outer query.
  • Choose the ranker deliberately: ROW_NUMBER gives exactly N rows; RANK/DENSE_RANK would return more when there are ties at the cutoff.
  • Add a unique tie-break column to the ORDER BY so exactly N rows come back deterministically.

Given employees and their salaries, return the two highest-paid people in each department. Ties in salary are broken by the lower id, and each department should yield at most two rows.

Schema

CREATE TABLE employees (
    id         INT,
    name       TEXT,
    department TEXT,
    salary     INT
);
idnamedepartmentsalary
1AnnEng150
2BobEng140
3CaraEng140
4DanSales90
5EveSales120
6FinnSales120
7GilHR80

Task

Return the top two earners per department. Rank by salary descending, breaking ties by id ascending. Output department, name, salary, and the within-department rank rn. Order the result by department ascending, then rn ascending.

Expected output

departmentnamesalaryrn
EngAnn1501
EngBob1402
HRGil801
SalesEve1201
SalesFinn1202
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.