Home › Interview Questions › Using the query SELECT salary FROM (SELECT salary,…

Using the query SELECT salary FROM (SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn FROM employees) t WHERE rn = 3; how would you modify it to correctly handle duplicate salaries when retrieving the third highest salary?

🟡 Medium Conceptual Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

ROW_NUMBER() assigns a unique sequential number to each row within the result set, regardless of duplicate values. When you want the third highest salary, duplicates can cause the row number to skip values. For example, if the salaries are 100, 90, 90, 80, the third highest salary is 90, but ROW_NUMBER() will return 1 for 100, 2 for the first 90, 3 for the second 90, so the query returns 90 twice. To correctly handle duplicates, use a ranking function that collapses ties: DENSE_RANK() or RANK(). DENSE_RANK() gives the same rank to equal values and does not skip ranks, so the third highest salary can be retrieved with WHERE dense_rank = 3. Alternatively, you can use SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 2,1 in MySQL or OFFSET 2 FETCH NEXT 1 ROWS ONLY in SQL Server. These approaches ensure that duplicates are treated as a single rank, giving you the true third highest salary.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500