Quick revision
The short answer
One approach ranks distinct salaries with DENSE_RANK() and wraps the result in MAX(): SELECT MAX(salary) FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) r FROM employee WHERE salary IS NOT NULL) t WHERE r = 3. The other uses a scalar subquery around SELECT DISTINCT salary ... ORDER BY salary DESC LIMIT 1 OFFSET 2. In both, the outer aggregate or scalar subquery turns "no match" into one row with NULL, and ties and NULL salaries must be handled on purpose.
What to remember
In this answer, we wrote the third highest distinct salary two ways: DENSE_RANK() with an outer MAX(), and SELECT DISTINCT ... ORDER BY salary DESC LIMIT 1 OFFSET 2 inside a scalar subquery, which in MySQL can be written LIMIT 2, 1. Both return one row with NULL when no third value exists. DISTINCT and DENSE_RANK handle ties, where ROW_NUMBER would give a wrong answer, and NULL salaries must be filtered because PostgreSQL sorts them first in descending order. The old correlated COUNT(DISTINCT) form works everywhere but costs about n squared comparisons.
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.
One approach ranks distinct salaries with DENSE_RANK() and wraps the result in MAX(): SELECT MAX(salary) FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) r FROM employee WHERE salary IS NOT NULL) t WHERE r = 3. The other uses a scalar subquery around SELECT DISTINCT salary ... ORDER BY salary DESC LIMIT 1 OFFSET 2. In both, the outer aggregate or scalar subquery turns "no match" into one row with NULL, and ties and NULL salaries must be handled on purpose.
Why this question is asked
The Nth highest salary is one of the oldest SQL interview questions, and it survives because it hides three separate traps in one line of requirements: ties, NULL values, and the difference between returning nothing and returning one row with NULL. Interviewers want to see whether we notice all three, not just whether we know LIMIT. In this answer, we will set up a small table, write the window function approach, write the offset approach, look closely at ties and NULLs, compare with the old correlated subquery, and then answer the two follow-ups: N per department and N as a parameter in a MySQL function.
1Setting Up the Data and the Exact Requirement
"Third highest distinct salary" means we look at the different salary values, sorted from highest to lowest, and take the third one. If two people earn 100, the value 100 counts once. And when there are fewer than three distinct values, the query must still return exactly one row, with NULL in it, rather than an empty result. That matters to callers: a Java method reading the result with queryForObject expects one row, and an empty result would throw an exception instead of giving null.
2Approach 1: DENSE_RANK and an Outer MAX
DENSE_RANK() is a window function: it gives each row a rank based on an ordering, without collapsing rows. Rows with equal salaries get the same rank, and the next value gets the next number, with no gaps. So 100 and 100 both get 1, 90 gets 2 and 80 gets 3. We filter on the rank in an outer query, because window functions are computed after WHERE and cannot be filtered in the same query level.
The outer MAX() is the trick that gives us one row. An aggregate without GROUP BY always returns exactly one row, and over zero input rows MAX() returns NULL. Several rows can have rank 3 when people tie, and MAX() also collapses those into one value.
3Approach 2: DISTINCT, LIMIT and OFFSET in a Scalar Subquery
The second approach sorts the distinct values and skips the first two. On its own, that query returns zero rows when there is no third value. Wrapping it as a scalar subquery, a subquery used as a single value, fixes that: a scalar subquery that finds no row yields NULL.
With an index on salary this version can be very fast, because the database can walk the index from the highest value and stop early. The DENSE_RANK version is often clearer when the question grows, for example to per-department ranks.
4Why Ties and NULLs Change the Answer
The word distinct is doing real work. With salaries 100, 100 and 90, there is no third highest distinct salary, so the right answer is NULL. ROW_NUMBER() would number the rows 1, 2, 3 and return 90, and plain ORDER BY ... OFFSET 2 without DISTINCT would also return 90. Both are wrong for this requirement.
NULL salaries are the quieter trap. In PostgreSQL, ORDER BY salary DESC puts NULLs first, because NULL sorts as larger than every value by default. Without the WHERE salary IS NOT NULL filter, Fay's NULL would get rank 1 and every real salary would move down one place. MySQL sorts NULLs last for DESC, so the same query gives different answers on the two databases unless we filter. In PostgreSQL, ORDER BY salary DESC NULLS LAST also works.
| salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 100 | 2 | 1 | 1 |
| 90 | 3 | 3 | 2 |
| 80 | 4 | 4 | 3 |
DENSE_RANK numbers distinct values: the third distinct salary is 80.5The Old Correlated Subquery
Before window functions, people wrote the question as "find the salary that exactly two distinct salaries are higher than". It works on every database, but for each row it counts over the whole table again.
For n rows that is about n x n comparisons, so a table of 100,000 employees means billions of comparisons unless an index helps. It is worth recognizing, but the two approaches above are what we should write today.
6The Follow-Ups: Per Department and a Parameter N
For the Nth highest salary per department, we add PARTITION BY dept_id, so ranks restart in each department. To return NULL for departments with fewer than N distinct salaries, we start from the department list and LEFT JOIN the ranked salaries.
Inside a MySQL stored program, LIMIT accepts a parameter or local variable, but not an arithmetic expression, which is why we decrement n first. We should also reject n below 1. In application code we would simply bind the offset as a parameter instead.
7Follow-up questions
How would you return the Nth highest salary for each department?
Rank with DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC), filter the rank in an outer query, and LEFT JOIN from the list of departments so that departments with fewer than N distinct salaries still appear with NULL, as in the last section.
What changes if N comes from a parameter in a MySQL stored function?
LIMIT inside a stored program accepts a variable but not an expression, so we compute the offset first with SET n = n - 1 and use LIMIT n, 1. We also validate that n is at least 1, because a negative variable in LIMIT raises an error.
Why does the query return a row with NULL instead of no rows?
Because the result is an aggregate or a scalar subquery. An aggregate without GROUP BY always returns one row, and a scalar subquery with no result is NULL. A plain SELECT ... LIMIT 1 OFFSET 2 would return an empty result.
8Conclusion
In this answer, we wrote the third highest distinct salary two ways: DENSE_RANK() with an outer MAX(), and SELECT DISTINCT ... ORDER BY salary DESC LIMIT 1 OFFSET 2 inside a scalar subquery, which in MySQL can be written LIMIT 2, 1. Both return one row with NULL when no third value exists. DISTINCT and DENSE_RANK handle ties, where ROW_NUMBER would give a wrong answer, and NULL salaries must be filtered because PostgreSQL sorts them first in descending order. The old correlated COUNT(DISTINCT) form works everywhere but costs about n squared comparisons.
Open with
First I would pin down the requirement: third highest distinct value, and one row with NULL if it does not exist. My first approach ranks with DENSE_RANK over salary descending in a subquery, filters rank equals three outside, because window functions run after WHERE, and wraps it in MAX.
Then, if they want more
The MAX matters: an aggregate without group by always returns one row, NULL when nothing matched, and it also collapses ties at rank three. The second approach is select distinct salary order by salary descending limit one offset two, used as a scalar subquery, which also turns an empty result into NULL; in MySQL it is limit two comma one.
Then the traps. Ties: with 100, 100 and 90 there is no third distinct salary, but ROW_NUMBER or a plain offset without distinct would return 90. NULLs: PostgreSQL sorts NULL first in descending order, so a NULL salary would take rank one and shift everything; I filter salary is not null or use nulls last, while MySQL sorts NULLs last.
The old correlated form, where two equals the count of distinct higher salaries, works everywhere but is quadratic without help. For per-department I would partition the DENSE_RANK by department and left join from departments, and in a MySQL function I would decrement N first because LIMIT takes a variable but not an expression.
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 "Table employee(id int primary key, name text, dept_id int, salary numeric). Write a...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/8a90deb117/