Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A report should show the second highest salary. The query is:

SQL
SELECT salary
FROM (SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) rn
FROM employee) t
WHERE rn = 2;

With salaries 100, 100, 90 it returns 100. Explain the bug, fix it, and say how the fixed query behaves on a 50 million row table with an index on salary.

ROW_NUMBER() gives tied rows different numbers, so the second 100 gets rn = 2 and the query returns 100. If the report means the second distinct value, we use DENSE_RANK or SELECT DISTINCT salary ORDER BY salary DESC LIMIT 1 OFFSET 1, after agreeing the definition with the report owner. With a B-tree index on salary, the offset query or a MAX(salary) below the maximum reads only a few index entries, while a window over all 50 million rows sorts or scans everything unless PostgreSQL 15 and later can stop early with a run condition.

Why this question is asked

This bug looks small, but it is a perfect example of a query that is syntactically right and semantically wrong. It passes every test with distinct salaries and fails the moment two people earn the same amount, which in a real company happens all the time. Interviewers ask it to see whether we can explain why the result is wrong, whether we ask what "second highest" means before fixing it, and whether we think about how the fix behaves on a big table. In this answer, we will reproduce the bug, look at the three ranking functions, agree the definition, write the fix, measure it on 50 million rows with EXPLAIN, and add a test so the tie case never comes back.

1Reproducing the Bug

Let us run the report query on the data from the question: salaries 100, 100 and 90.

SQL
SELECT salary
FROM (SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) rn FROM employee) t
WHERE rn = 2;
-- 100
SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) rn FROM employee;
-- 100 | 1
-- 100 | 2 the second 100 is "row 2"
-- 90 | 3

ROW_NUMBER() numbers rows one after another, 1, 2, 3, and it never gives two rows the same number. When salaries tie, it still has to put one of them first, and it chooses arbitrarily. So rn = 2 is simply the second row of the sorted list, which here is the second person earning 100. The query does exactly what it says; it just says the wrong thing.

2Three Ranking Functions, Three Answers

SQL has three ranking window functions, and they differ only in how they treat ties. ROW_NUMBER() gives unique numbers. RANK() gives tied rows the same number and then skips, like a sports table where two runners share first place and the next one is third. DENSE_RANK() gives tied rows the same number and does not skip, so it numbers distinct values.

Salaries 100, 100, 90 ranked three ways
salaryROW_NUMBERRANKDENSE_RANK
100111
100211
90332
result of = 2100no row90

Applied to our data, rn = 2 means three different things. With ROW_NUMBER it returns 100, the second row. With RANK it returns nothing at all, because the ranks are 1, 1, 3 and no row has rank 2. With DENSE_RANK it returns 90, the second distinct value. That is why the fix starts with a question rather than with code.

3Agreeing the Definition Before Fixing

So which answer is right? It depends on what the report owner means. "The second highest salary in the company" usually means the second distinct value, 90. "The salary of the second best-paid person" is the second row, 100. "Who is in second place" in a ranking with ties is RANK, which says nobody is second because two people share first. Each is a legitimate business question.

In most salary reports the meaning is the second distinct value, but I would confirm it with the owner and write the definition next to the query, for example in a comment or the report's description. Otherwise the next person to touch it will change the function again.

4The Fix and Its Two Forms

Assuming the owner wants the second distinct value, there are two clean fixes. Both also need the NULL filter, because PostgreSQL sorts NULL first in descending order.

SQL
-- Fix A: DENSE_RANK
SELECT MAX(salary) FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r
FROM employee WHERE salary IS NOT NULL) t
WHERE r = 2;
-- 90
-- Fix B: distinct values with an offset
SELECT (SELECT DISTINCT salary FROM employee
WHERE salary IS NOT NULL
ORDER BY salary DESC LIMIT 1 OFFSET 1) AS second;
-- 90
-- Fix C, only for the second value: the highest salary below the maximum
SELECT MAX(salary) FROM employee
WHERE salary < (SELECT MAX(salary) FROM employee);
-- 90

Notice that all three return one row, with NULL when there is no second value, because of the outer MAX() or the scalar subquery. That keeps the report from failing on a small table.

5How the Fix Behaves on 50 Million Rows

Now the performance part. A B-tree index on salary keeps the values sorted, and PostgreSQL can read it backwards, from the highest value down. Fix C needs two index lookups: one for the maximum and one for the largest value below it, so it costs microseconds no matter how big the table is. Fix B walks the index backwards and stops after it has found two distinct values, but DISTINCT has to step over every duplicate of the top value first; if 200,000 people share the top salary, it reads 200,000 index entries.

The window version is the risky one. A window function needs all its input in order, so in the simplest plan PostgreSQL sorts all 50 million salaries, or reads the whole index, ranks every row and then keeps those with r = 2. Since PostgreSQL 15, the planner can attach a run condition to monotonic window functions such as row_number, rank and dense_rank, so a filter like r <= 2 lets the WindowAgg stop as soon as the rank passes 2, and combined with an index scan it reads only a few rows. Which filter forms qualify depends on the version, so check your version with EXPLAIN. MySQL 8 materializes the window result and does not stop early this way.

Java
EXPLAIN (ANALYZE, BUFFERS)
SELECT (SELECT DISTINCT salary FROM employee WHERE salary IS NOT NULL
ORDER BY salary DESC LIMIT 1 OFFSET 1);
-- Limit (actual rows=1)
-- -> Unique (actual rows=2)
-- -> Index Only Scan Backward using employee_salary_idx (actual rows=4)
-- Heap Fetches: 0
-- Buffers: shared hit=5
-- Execution Time: 0.06 ms
Step throughChecking the plan of the fixed query
  1. Run EXPLAIN (ANALYZE, BUFFERS)on production-sized data
  2. Index scan backward, no Sort node?
    YesCheck rows and buffers are smallNoFind why the index is skipped
  3. Rows read in the thousands or fewer?
    YesDone: ship with a tie testNoMany duplicates of the top value: use Fix C

3 steps in order. Play them, or step through them one at a time.

This is what we want to see: an index scan read backwards, a handful of rows and buffers, and no Sort node. If the plan instead shows a Sort over 50 million rows or a Seq Scan, the index is not being used, perhaps because of a missing NULL filter, a different collation or a function around the column.

6Testing So the Tie Case Never Regresses

The original bug survived because the test data had no ties. A good test suite for this query includes ties at the top, ties at the target position, NULL salaries, and fewer distinct values than requested, each with the expected result written down. With Spring Boot I would run these against the real database engine with Testcontainers, because NULL ordering differs between PostgreSQL and MySQL, and an in-memory database may not behave like either.

Java
@Test
void secondHighestIgnoresTiesAtTheTop() {
insertSalaries(100, 100, 90);
assertThat(repo.secondHighestSalary()).isEqualByComparingTo("90");
}
@Test
void secondHighestIsNullWhenOnlyOneDistinctValue() {
insertSalaries(100, 100);
assertThat(repo.secondHighestSalary()).isNull();
}

7Follow-up questions

Which result would RANK() give here?

None. RANK() gives both 100s rank 1 and the 90 rank 3, skipping 2, so WHERE rn = 2 matches no row. Wrapped in MAX(), it would return NULL, which tells the report there is no one in second place.

How would you test this query so the tie case never regresses?

Write tests with ties at the top, a tie at the target position, NULL salaries and too few distinct values, each with the agreed expected result, and run them against the real engine with Testcontainers in the build.

Is DENSE_RANK ever slower than the offset query?

Often, on large tables, because the window may rank every row unless the planner can use a run condition. For a single value, the offset or MAX-below-MAX query with an index is usually cheaper, while DENSE_RANK is clearer for per-group rankings.

8Conclusion

In this answer, we saw that ROW_NUMBER() gives tied rows different numbers, so the second 100 got rn = 2. RANK() would return no row and DENSE_RANK() returns the second distinct value, 90, which is why we first agree the definition with the report owner. With a B-tree index on salary, the DISTINCT ... OFFSET 1 query or MAX below the maximum reads only a few index entries, while a window over 50 million rows sorts or scans everything unless PostgreSQL 15 and later can stop early with a run condition, and MySQL materializes the window. We confirm the plan with EXPLAIN (ANALYZE, BUFFERS) and lock the tie case in with tests.

What to say in the interviewAbout 100 seconds aloud

Open with

The bug is that ROW_NUMBER gives every row a unique number even when values tie. With 100, 100 and 90, the second 100 becomes row two, so the query returns 100.

Then, if they want more

Before fixing it, I would ask the report owner what second highest means, because there are three answers: the second row is 100, the second distinct value is 90, and with RANK there is no second place at all, since the ranks are one, one, three.

Usually it means the second distinct value, so I would use DENSE_RANK wrapped in MAX, or select distinct salary order by salary descending limit one offset one as a scalar subquery, both with a salary is not null filter because PostgreSQL sorts NULL first in descending order.

For just the second value, max salary below the max is the cheapest of all. On 50 million rows with an index on salary, the offset query reads the index backwards and stops after a few entries, though distinct has to skip every duplicate of the top value.

A window function would normally rank every row after a sort or full index scan; PostgreSQL 15 and later can stop early with a run condition on filters like rank less than or equal to two, so I would check with EXPLAIN ANALYZE BUFFERS that I see a backward index scan with tiny row counts and no sort.

MySQL materializes the window. Finally I would add tests with ties and NULLs on the real engine.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 15, MySQL 8
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 "A report should show the second highest salary. The query is:": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/aca4849249/