Top 3 Earners Per Department (ROW_NUMBER ≤ 3)
List the three highest-paid employees in each department, with their in-department rank. Return department_name, first_name, last_name, salary, dept_rank — ordered by department_name, dept_rank.
- CTEs
- Window functions
- Joins
- Subqueries
- Filtering
Interview brief
Understand the request
List the three highest-paid employees in each department, with their in-department rank. Return department_name, first_name, last_name, salary, dept_rank — ordered by department_name, dept_rank.
Data you will use
Review the relevant tables before deciding how to join, filter, or aggregate them.
employees
employee_idINTEGERfirst_nameVARCHAR(50)last_nameVARCHAR(50)salaryINTEGERdepartment_idINTEGER
departments
department_idINTEGERdepartment_nameVARCHAR(50)
Hints, when you need them
Open one clue at a time so you still do the reasoning.
Hint 1
Change the filter from rn = 1 to rn <= N for 'top N per group'.
Hint 2
Use ROW_NUMBER for exactly N rows; use RANK/DENSE_RANK if you want to INCLUDE ties at the cutoff.
Hint 3
Departments with fewer than 3 employees simply return all of theirs.
Verified SQL answer
Attempt the problem first, then compare structure and reasoning—not just syntax.
Reveal solution and explanation
WITH ranked AS (SELECT e.department_id, d.department_name, e.first_name, e.last_name, e.salary, ROW_NUMBER() OVER (PARTITION BY e.department_id ORDER BY e.salary DESC, e.employee_id) AS dept_rank FROM employees e INNER JOIN departments d ON e.department_id = d.department_id) SELECT department_name, first_name, last_name, salary, dept_rank FROM ranked WHERE dept_rank <= 3 ORDER BY department_name, dept_rank;Why this works
Top-N-per-group generalizes top-1: just widen the filter. The choice of ROW_NUMBER vs RANK/DENSE_RANK decides whether ties at the boundary push you over N rows. ROW_NUMBER caps it at exactly N.
Expected result
Use this output to verify values, aliases, ordering, and row count.
| department_name | first_name | last_name | salary | dept_rank |
|---|---|---|---|---|
| Engineering | Michael | Scott | 180000 | 1 |
| Engineering | David | Martinez | 130000 | 2 |
| Engineering | Emily | Chen | 125000 | 3 |
| Executive | Jennifer | King | 250000 | 1 |
| Finance | Jessica | Moore | 105000 | 1 |
| Finance | Daniel | Lee | 70000 | 2 |
| Human Resources | Patricia | Davis | 95000 | 1 |
| Human Resources | Christopher | Wilson | 65000 | 2 |
| Sales | Sarah | Johnson | 175000 | 1 |
| Sales | James | Taylor | 110000 | 2 |
Previewing 10 of 11 expected rows. Run the query in the editor to inspect the full result.
Learn the concepts behind this answer
Strengthen your understanding with these targeted learning topics: