Quick revision
The short answer
We rank employees inside each department with a window function and filter the rank in an outer query: SELECT * FROM (SELECT e.*, DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) r FROM employee e) t WHERE r <= 3. DENSE_RANK keeps everyone tied for third, so a department can return more than three people; ROW_NUMBER with a tie-breaker returns exactly three. For one top earner per department, PostgreSQL's DISTINCT ON (dept_id) with ORDER BY dept_id, salary DESC, id is the shortest form.
What to remember
In this answer, we returned the top three earners per department by computing DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) in a subquery and filtering r <= 3 outside, because WHERE runs before window functions. DENSE_RANK and RANK keep everyone tied for third, so a department can return more than three people, while ROW_NUMBER returns exactly three and needs a tie-breaker such as id to be deterministic. For one top earner, PostgreSQL's DISTINCT ON (dept_id) with ORDER BY dept_id, salary DESC, id is the shortest form, and a LATERAL subquery with ORDER BY ... LIMIT 3 is the alternative that uses an index on (dept_id, salary DESC) best.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We rank employees inside each department with a window function and filter the rank in an outer query: SELECT * FROM (SELECT e.*, DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) r FROM employee e) t WHERE r <= 3. DENSE_RANK keeps everyone tied for third, so a department can return more than three people; ROW_NUMBER with a tie-breaker returns exactly three. For one top earner per department, PostgreSQL's DISTINCT ON (dept_id) with ORDER BY dept_id, salary DESC, id is the shortest form.
Why this question is asked
Top N per group is one of the most useful SQL patterns there is: the three latest orders per customer, the best-selling product per category, the top earners per department. It also appears in interviews constantly, because the obvious attempt, a WHERE clause on a window function, does not work, and because ties make "top 3" ambiguous. In this answer, we will set up data with a tie, see why the window must be filtered outside, compare ROW_NUMBER, RANK and DENSE_RANK on the tie, write the one-per-department variant with DISTINCT ON, and look at a LATERAL version that uses an index well.
1Setting Up Data With a Tie
We need ties to see the differences, so department 10 has two people sharing the third highest salary.
2Why the Window Must Be Filtered Outside
A window function computes a value for each row over a group of related rows, without collapsing them like GROUP BY does. PARTITION BY dept_id restarts the calculation for each department, and ORDER BY salary DESC decides the ranking order within it.
The natural first attempt is to filter in the same query, and it fails. The reason is the order in which SQL evaluates a query: FROM, then WHERE, then GROUP BY and HAVING, then window functions, then SELECT's output, then ORDER BY and LIMIT. When WHERE runs, the rank does not exist yet. So we compute the rank in a subquery or CTE and filter it in the outer query.
Notice that department 10 returns four people, because Cara and Dev share rank 3, and department 20 returns only two, because it has only two employees. Both are correct for "everyone whose salary is among the top three salaries".
3What Each Ranking Function Does With the Tie
The three ranking functions differ only in ties. ROW_NUMBER() gives every row a different number, so it returns exactly three rows per department, and which of Cara or Dev gets number 3 is arbitrary unless we add a tie-breaker such as id to the ORDER BY. An arbitrary choice is a real bug: the same report can show Cara today and Dev tomorrow. RANK() gives ties the same number and then skips, like a sports table. DENSE_RANK() gives ties the same number and does not skip.
| name, salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| Ana, 120 | 1 | 1 | 1 |
| Ben, 110 | 2 | 2 | 2 |
| Cara, 100 | 3 | 3 | 3 |
| Dev, 100 | 4 (with id tie-breaker) | 3 | 3 |
| Eli, 90 | 5 | 5 | 4 |
ROW_NUMBER drops Dev, RANK and DENSE_RANK keep both people tied for third.So the right function depends on what the business means. "Exactly three names for the award" is ROW_NUMBER with a fair tie-breaker. "Anyone in the top three places" is RANK. "Anyone earning one of the three highest salaries" is DENSE_RANK. Here RANK and DENSE_RANK give the same result for r <= 3, but with a tie at first place they would differ: with salaries 120, 120, 110, 100, RANK gives 1, 1, 3, 4 and returns three people, while DENSE_RANK gives 1, 1, 2, 3 and returns four.
4Exactly One Top Earner per Department With DISTINCT ON
For the single top earner, PostgreSQL has a compact extension. DISTINCT ON (dept_id) keeps the first row of each dept_id group, where "first" is decided by the ORDER BY. The ORDER BY must start with the DISTINCT ON columns, and the columns after them pick the winner.
The id at the end is the tie-breaker. If two people tied for first, the one with the lower id would win, consistently. DISTINCT ON always returns exactly one row per group, so it is the same as ROW_NUMBER() = 1, not RANK() = 1. It is PostgreSQL only; on MySQL we use the ROW_NUMBER form.
5A LATERAL Version That Uses an Index
There is also a version without window functions. LATERAL lets a subquery in FROM refer to columns of tables listed before it, so we can run a small "top 3 by salary" query once per department.
This behaves like ROW_NUMBER, exactly three per department. With the index on (dept_id, salary DESC), each inner query jumps to its department in the index, reads three entries in order and stops. In a real schema we would take the department list from a department table rather than SELECT DISTINCT, which itself reads the employee table. The window version, by contrast, reads every employee before it can rank, so the LATERAL version wins when departments are large and N is small, and the window version is simpler and fine when we need most of each group anyway.
6Follow-up questions
Which approach can use an index on (dept_id, salary DESC) best?
The LATERAL query with ORDER BY salary DESC LIMIT 3, because each probe is an index range scan that stops after three entries. The window version can use the index to avoid a sort, but it still reads every row of every department. DISTINCT ON can also read the index in order, though it scans all rows unless the planner can skip between groups.
Can we filter a window function with QUALIFY?
Some databases support a QUALIFY clause that filters on window results directly, but PostgreSQL and MySQL do not, so check your version. In both we use a subquery or CTE.
How do we include departments with no employees?
Start from the department table and use LEFT JOIN LATERAL ... ON true, or LEFT JOIN the ranked subquery. CROSS JOIN LATERAL drops a department whose inner query returns no rows.
7Conclusion
In this answer, we returned the top three earners per department by computing DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) in a subquery and filtering r <= 3 outside, because WHERE runs before window functions. DENSE_RANK and RANK keep everyone tied for third, so a department can return more than three people, while ROW_NUMBER returns exactly three and needs a tie-breaker such as id to be deterministic. For one top earner, PostgreSQL's DISTINCT ON (dept_id) with ORDER BY dept_id, salary DESC, id is the shortest form, and a LATERAL subquery with ORDER BY ... LIMIT 3 is the alternative that uses an index on (dept_id, salary DESC) best.
Open with
I would compute DENSE_RANK over partition by department order by salary descending in a subquery, and filter rank less than or equal to three in the outer query.
Then, if they want more
It has to be outside because SQL evaluates WHERE before window functions, so the rank does not exist yet in the same query level. On ties: with DENSE_RANK, if two people tie for third, both come back, so a department can return four or more rows, and a small department returns fewer than three.
If the business wants exactly three names, I use ROW_NUMBER, but then I must add a tie-breaker like id to the order by, otherwise which of the tied people appears is arbitrary and can change between runs. RANK also keeps ties but skips numbers after them, so with a tie at first place it can return fewer people than DENSE_RANK.
For exactly one top earner per department in PostgreSQL, I would use select distinct on department from employee order by department, salary descending, id, which keeps the first row per department and behaves like ROW_NUMBER equals one. And there is a version without windows: a lateral subquery per department with order by salary descending limit three.
With an index on department and salary descending, that is an index range scan per department that stops after three rows, so it is the best choice when departments are large.
About this answer
- Last updated
- 12 November 2026
- 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.
- Official documentation
- PostgreSQL documentation, The SQL Language
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 "Using employee(id, name, dept_id, salary), return the top 3 earners in each department....": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/871b2d7b96/