Skip to the solution
MediumDSA8 min read

How do you find the Nth highest salary?

516 views

The problem

Question presented to candidate: "Given an employees table with a salary column, write a query that returns the third highest salary. Then make it work for any N, and tell me what your query does when two people earn the same amount, when some salaries are NULL, and when there are fewer than N distinct salaries."

What a strong answer should cover:

  • Clarify "Nth highest": the Nth distinct salary value (ties count once) or the Nth row; the classic answer means distinct values
  • DENSE_RANK() OVER (ORDER BY salary DESC) and filter = N, which returns every employee at that salary; why ROW_NUMBER() and RANK() give different answers on ties
  • Without window functions: SELECT DISTINCT salary ... ORDER BY salary DESC LIMIT 1 OFFSET N-1, or the correlated "N-1 distinct salaries are higher" subquery
  • Fewer than N salaries: a bare LIMIT/OFFSET returns no row; wrapping it in a scalar subquery returns NULL instead
  • NULL salaries: PostgreSQL sorts NULL first in DESC order, so the "highest" can be NULL unless you filter it or write NULLS LAST; SQLite, MySQL and SQL Server sort it last in DESC
  • Per group (Nth highest per department) with PARTITION BY, and the cost: one sort of the table, helped by an index on salary

Clarifying questions expected:

  • If two employees share the top salary, is the next one the 2nd or the 3rd highest?
  • Should the result be the salary value or the employees who earn it?
  • What should come back when there is no Nth salary: no row, or NULL?

Code / implementation expected: Yes β€” a DENSE_RANK() query, and one approach that works without window functions.

Schema used by the examples:

  • nth-highest

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read Β· 12 sections

Run the code

Edit the query and run it against the tables for this question.

SQLROW_NUMBER vs RANK vs DENSE_RANK on tied salaries, then the 3rd highest with DENSE_RANK
SQLDISTINCT + LIMIT/OFFSET wrapped in a scalar subquery: NULL when there is no Nth salary
SQLNo window functions, no LIMIT: exactly N-1 distinct salaries are higher
PostgreSQL trap: NULL sorts first in DESC order, so it takes rank 1
SELECT name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS dense
FROM employees
ORDER BY salary DESC, id
LIMIT 4;

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 53 of 82 in SQL

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All SQL questions
Up nextMedium

What are window functions?

Continue