Answer
The second-highest distinct salary can be selected by ranking distinct salary values. • DENSE_RANK assigns consecutive ranks to distinct ordered values. • Filtering rank 2 handles duplicate highest salaries correctly. • Define how NULL salaries should be treated for the interview question.
💡 SQL Example
SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank FROM employees WHERE salary IS NOT NULL) ranked WHERE salary_rank = 2;
Result
The second-highest distinct salary
⚡ Quick Revision
Rank distinct salary levels and select rank 2.