SQL Quest › SQL Interview Questions › Window Functions

Salary Rank Within Department

HardFreeQuerying BasicsWindow Functions

Write a SQL query to rank employees by salary within each department. Return name, department, salary, and dept_rank (1 = highest paid in dept). Use dense ranking (no gaps). Order the rows by department ascending, then dept_rank ascending, then name ascending.

Solve it in the browser editor →

Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect". Free accounts get 10 free challenge solves, and this can be one of them.

Schema

employees

emp_idnamedepartmentpositionsalaryhire_datemanager_idperformance_rating
1Alice JohnsonEngineeringSenior Developer950002019-03-1554.5
2Bob SmithEngineeringDeveloper750002020-06-0113.8
3Carol WilliamsMarketingMarketing Manager850002018-09-20NULL4.2

Expected output: All employees with their salary rank in their department

Hint

Use DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) for the rank column. Then finish with an outer ORDER BY so the rows themselves come back in a deterministic order — window functions don't sort the result for you.

Concepts

SELECT Window Functions ORDER BY Window Function

Practise the topic: SQL practice questions · Window function practice · Ranking function practice · Advanced SQL interview questions

Read the concept: SQL running total

In these company practice sets

NVIDIA · Snowflake · LinkedIn · Microsoft

A SQL Quest challenge matched to patterns reported for these companies — not a question any of them has published.

Related questions

First and Last Order per CustomerHard · ProCumulative Revenue Share (Pareto)Hard · ProMoving Average with Dynamic WindowHard · ProRank Movies by RatingHard · ProSalary Lead-Lag Gap Within DepartmentHard · ProTop Earner Per DepartmentHard · Pro

Where would this cost you points in an interview?

Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.

Take the readiness test