← Back ← LAG Date cheatsheet →

Top 3 salaries per department

DENSE_RANK + PARTITION BY inside a subquery — then filter

SQL drill • Window functions

Table employees(department, employee, salary). Return department, employee, and salary for everyone in the top three salary tiers within each department: rank by salary descending with DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC), then keep rows where rank ≤ 3. Use the derived-table pattern: inner query adds rank, outer query selects columns and filters.
Standard SQL does not let you reference the window alias in the same SELECT level as WHERE — so nest the ranked result, then filter. Ties share a rank; with DENSE_RANK, rank 3 can still include many rows if many people tie at the third tier.

Pattern
Inner rank → AS ranked → WHERE ≤ 3
Step 0/8Line
Rank inside subquery → filter outside
Press Step or Play.
Ready
Inner query: add rank per department. Outer query: pick columns and keep rank ≤ 3.