Hard Window functions and CASE Employees database

Rank within groups with a window function

Question

Show each employee's name, department_id and salary, plus their salary rank inside their own department (1 = highest paid).

employeesid, name, salary, department_id, manager_id, hired_on
departmentsid, name, city

Your query

Ctrl+Enter to run

Result

Press Run to see your query's result, or Check answer to compare it with the expected result.

Expected result

namedepartment_idsalarydept_rank
Priya Nair192001
Tom Becker188002
Mei Chen176003
Hana Kim173004
Lucas Moreau268001
Ana Souza265002
Omar Haddad256003
Sofia Rossi361001
Jonas Berg354002
Aisha Bello447001
Liam Walsh443002
Diego Ruiz441003

Rows can come in any order. Column names do not have to match.

Hint

RANK() OVER (PARTITION BY ... ORDER BY ...) restarts the ranking for every department.

Show the solution
solution.sql Run this code
SELECT name, department_id, salary,
       RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS dept_rank
FROM employees;

Why it works

A window function calculates a value for every row while looking at a group of related rows. PARTITION BY makes one window per department, and ORDER BY salary DESC decides who is first.

Common mistake

Unlike GROUP BY, a window function does not collapse rows. Every employee stays in the result; they just get an extra column.

Want to try the query on MySQL or PostgreSQL? Open it in the SQL Online Compiler or SQLite Online.