HomeInterview QuestionsGiven the same query, how would you adjust it to a…

Given the same query, how would you adjust it to account for duplicate salaries when selecting the third highest salary?

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

💡 Model Answer

ROW_NUMBER() assigns a unique number to each row, so duplicates receive separate numbers. To get the third highest distinct salary, replace ROW_NUMBER() with DENSE_RANK() or RANK(). For example: SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS dr FROM employees) t WHERE dr = 3;. DENSE_RANK() assigns the same rank to equal salaries and does not skip ranks, so the third distinct salary is returned. If you prefer a simpler approach, use SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 2,1 (MySQL) or OFFSET 2 FETCH NEXT 1 ROWS ONLY (SQL Server). These queries treat duplicates as a single value, ensuring the correct third highest salary is retrieved. Another option is to use a subquery that first selects distinct salaries: SELECT salary FROM (SELECT DISTINCT salary FROM employees ORDER BY salary DESC) sub LIMIT 2,1;. This method is database‑agnostic and works in PostgreSQL, MySQL, and SQL Server. Remember that if the table contains many rows, adding an index on the salary column will improve performance for the ORDER BY and LIMIT operations.

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