Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Return the top 3 highest-paid employees per department from employees(id, dept_id, salary), and explain how ROW_NUMBER, RANK and DENSE_RANK differ when two people have the same salary.

We rank employees within each department and keep the top three: SELECT * FROM (SELECT e.*, DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS r FROM employees e) t WHERE r <= 3. With two people on the same salary, ROW_NUMBER gives them different numbers in an arbitrary order, RANK gives them the same rank and skips the next (1, 1, 3), and DENSE_RANK gives the same rank without skipping (1, 1, 2). Which one is right depends on the business rule: exactly three rows, or everyone in the top three salaries.

Why this question is asked

Top-N per group is probably the most asked window function question, and for good reason: it appears in leaderboards, 'latest three orders per customer', 'best-selling products per category', and the answer changes with the treatment of ties. Interviewers want to see that we can write the query, that we know why the filter needs a subquery, and above all that we ask what should happen when two people earn the same. In this answer, we will see why GROUP BY cannot do this, write the query, compare the three ranking functions on tied data, connect the choice to the business rule, and make it fast with the right index.

1Why GROUP BY Cannot Do Top-N Per Group

GROUP BY dept_id can tell us the maximum salary in each department, but only one value per group. It cannot return the three rows with the highest salaries, because grouping removes the individual rows.

A window function solves this. It computes a value for each row over a set of related rows, its window, without collapsing them. PARTITION BY dept_id makes each department a separate window, and ORDER BY salary DESC inside the window lets a ranking function number the rows from the highest salary down.

2Writing the Query

Here is the data we will use. Department 10 has a tie for second place.

SQL
-- employees (id, dept_id, salary)
-- 1, 10, 9000 2, 10, 8000 3, 10, 8000 4, 10, 7000 5, 10, 6000
-- 6, 20, 5000 7, 20, 4000
SELECT *
FROM (
SELECT e.*, DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS r
FROM employees e
) t
WHERE r <= 3
ORDER BY dept_id, r;
-- 1 | 10 | 9000 | 1
-- 2 | 10 | 8000 | 2
-- 3 | 10 | 8000 | 2
-- 4 | 10 | 7000 | 3
-- 6 | 20 | 5000 | 1
-- 7 | 20 | 4000 | 2

Department 10 returns four people, because two share the second-highest salary, and department 20 returns its only two people. Notice the subquery. Window functions are computed after WHERE, so we cannot write WHERE DENSE_RANK() OVER (...) <= 3 in the same SELECT; the rank does not exist yet when WHERE runs. We compute it in an inner query, or a CTE, and filter outside.

3ROW_NUMBER, RANK and DENSE_RANK on Tied Salaries

The three functions differ only in how they treat rows that are equal in the ORDER BY, called peers. Running all three side by side on department 10 makes the difference visible.

SQL
SELECT id, salary,
ROW_NUMBER() OVER w AS row_num,
RANK() OVER w AS rnk,
DENSE_RANK() OVER w AS dense
FROM employees
WHERE dept_id = 10
WINDOW w AS (ORDER BY salary DESC);
-- 1 | 9000 | 1 | 1 | 1
-- 2 | 8000 | 2 | 2 | 2
-- 3 | 8000 | 3 | 2 | 2
-- 4 | 7000 | 4 | 4 | 3
-- 5 | 6000 | 5 | 5 | 4
Top 3 of department 10 by each function
FunctionRanks givenRows with r <= 3Meaning
ROW_NUMBER1, 2, 3, 4, 53 rows (tie broken arbitrarily)Exactly three people
RANK1, 2, 2, 4, 53 rows here, can be moreTop three positions, gaps after ties
DENSE_RANK1, 2, 2, 3, 44 rowsEveryone in the top three salary values

ROW_NUMBER always gives unique numbers 1, 2, 3, and so on. Between employees 2 and 3, who earn the same, the order is arbitrary: the database may return them either way, and may change between runs or after a plan change. To make it stable we add a tiebreaker, ORDER BY salary DESC, id.

RANK gives peers the same rank and then skips, the way sports results do: two people tie for second, and the next person is fourth, so we see 1, 2, 2, 4. DENSE_RANK gives peers the same rank without gaps: 1, 2, 2, 3. So with r <= 3, RANK returns three people (ranks 1, 2, 2) and DENSE_RANK returns four (ranks 1, 2, 2, 3).

4Choosing by the Business Rule

The choice is not a technical preference; it is a question for whoever owns the report. If the rule is 'show exactly three people per department on the dashboard tile', ROW_NUMBER with a deterministic tiebreaker is right, and we document how ties are broken, for example by earlier hire date. If the rule is 'everyone whose salary is among the three highest salaries', DENSE_RANK is right and the number of rows can grow with ties. If the rule follows competition-style positions, 'anyone placed third or better', RANK is right.

In an interview, saying 'I would ask how ties should be handled, and here is what each option gives' is often worth more than the query itself, because a wrong choice here produces a plausible but incorrect report.

5Making It Fast With an Index

To rank, the database must read each department's rows in salary order. Without help, it sorts the whole table by dept_id and salary. An index on (dept_id, salary DESC) stores the rows in exactly that order, so the window can read them presorted and skip the sort.

Java
CREATE INDEX employees_dept_salary_idx ON employees (dept_id, salary DESC);
EXPLAIN SELECT ... ; -- the DENSE_RANK query
-- Subquery Scan on t (Filter: r <= 3)
-- -> WindowAgg
-- -> Index Scan using employees_dept_salary_idx on employees e

Notice that the filter r <= 3 still sits above the WindowAgg, so all rows are ranked even though we keep few. PostgreSQL 15 and later can stop the window computation early within each partition for some filters on ROW_NUMBER, RANK and DENSE_RANK (the plan shows a Run Condition), which helps here; check your version's plan. When departments are many and large and we need very few rows from each, a LATERAL join that runs ORDER BY salary DESC LIMIT 3 per department, backed by the same index, can be faster still.

6Follow-up questions

How do you make ROW_NUMBER deterministic?

Add columns to the window's ORDER BY until the order is unique, ideally ending with the primary key: ORDER BY salary DESC, hire_date, id. Then the same data always produces the same numbering, which matters for pagination and for tests.

Does this work in MySQL?

Yes, MySQL 8.0 and later support ROW_NUMBER, RANK and DENSE_RANK with PARTITION BY, and the query is the same. MySQL also requires the derived table to have an alias, which we gave as t. Earlier MySQL versions had no window functions and needed user-variable tricks, which are unreliable and should not be used today.

How would you return the top 3 salaries per department without duplicates of the same salary?

Select DISTINCT dept_id, salary first and then rank: SELECT dept_id, salary FROM (SELECT dept_id, salary, ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS r FROM (SELECT DISTINCT dept_id, salary FROM employees) s) t WHERE r <= 3. That returns salary values, not people, which is what some compensation reports want.

7Conclusion

In this answer, we returned the top three earners per department by ranking rows within each department in a subquery and filtering on the rank outside, because window functions are computed after WHERE. ROW_NUMBER gives unique numbers and needs a tiebreaker, RANK gives ties the same rank and skips (1, 1, 3), and DENSE_RANK gives ties the same rank without skipping (1, 1, 2). The right one depends on whether the business wants exactly three rows or everyone within the top three salaries, and an index on (dept_id, salary DESC) feeds the window presorted rows.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd rank inside each department with a window function and filter outside: SELECT star FROM (SELECT e.*, DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS r FROM employees e) t WHERE r is at most 3.

Then, if they want more

The subquery is needed because window functions are evaluated after WHERE, so I can't filter on the rank in the same SELECT. The interesting part is ties. ROW_NUMBER gives every row a unique number, so two people with the same salary get 2 and 3 in an arbitrary order unless I add a tiebreaker like id.

RANK gives them the same rank and then skips, so 1, 2, 2, 4. DENSE_RANK gives the same rank without gaps, 1, 2, 2, 3.

So with ROW_NUMBER I get exactly three people per department, with DENSE_RANK I get everyone whose salary is among the top three salary values, which can be more than three rows, and RANK sits in between. Which one is right is a business decision, so I'd ask.

For performance, an index on dept_id and salary descending lets the window read rows already in order and skip the sort, and on PostgreSQL 15 and later the planner can stop ranking early within each partition.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8.0, PostgreSQL 15
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Return the top 3 highest-paid employees per department from employees(id, dept_id...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/e013d83788/