Rank Employees by Salary (ROW_NUMBER)
Return each employee with their row number rank within their department by salary.
- CTEs
- Window functions
- Joins
- Sorting
Interview brief
Understand the request
People analytics analyst The salary ranking board assigns each employee a rank within their department using ROW_NUMBER.
Assign a unique row number to every employee ordered by salary descending (ties broken by employee_id). Return first_name, last_name, salary, department_name, row_num — ordered by row_num.
Return
- Return employee_name, department_id, salary, and dept_rank.
Constraints
- Use ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC).
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
ROW_NUMBER() always produces 1,2,3,… with no ties — even when the ORDER BY values are equal.
Hint 2
Add a tie-breaker (employee_id) inside OVER(ORDER BY …) so the numbering is deterministic.
Hint 3
Window functions do NOT collapse rows — every input row keeps its identity (unlike GROUP BY).
Verified SQL answer
Attempt the problem first, then compare structure and reasoning—not just syntax.
Reveal solution and explanation
SELECT e.first_name, e.last_name, e.salary, d.department_name, ROW_NUMBER() OVER (ORDER BY e.salary DESC, e.employee_id) AS row_num FROM employees e INNER JOIN departments d ON e.department_id = d.department_id ORDER BY row_num;Why this works
ROW_NUMBER is the simplest window function: it numbers rows within an ordering. Because it never ties, it's the backbone of 'top-N per group' and deduplication patterns (see Q11–Q13).
Expected result
Use this output to verify values, aliases, ordering, and row count.
| first_name | last_name | salary | department_name | row_num |
|---|---|---|---|---|
| Jennifer | King | 250000 | Executive | 1 |
| Michael | Scott | 180000 | Engineering | 2 |
| Sarah | Johnson | 175000 | Sales | 3 |
| David | Martinez | 130000 | Engineering | 4 |
| Emily | Chen | 125000 | Engineering | 5 |
| James | Taylor | 110000 | Sales | 6 |
| Jessica | Moore | 105000 | Finance | 7 |
| Robert | Williams | 95000 | Engineering | 8 |
| Patricia | Davis | 95000 | Human Resources | 9 |
| Lisa | Anderson | 90000 | Engineering | 10 |
Previewing 10 of 15 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: