Skip to content
Advertisement

How to get second-highest salary employees in a table

It’s a question I got this afternoon:

There a table contains ID, Name, and Salary of Employees, get names of the second-highest salary employees, in SQL Server

Here’s my answer, I just wrote it in paper and not sure that it’s perfectly valid, but it seems to work:

I think it’s ugly, but it’s the only solution come to my mind.

Can you suggest me a better query?

Thank you very much.

Advertisement

Answer

To get the names of the employees with the 2nd highest distinct salary amount you can use.

If Salary is indexed the following may well be more efficient though especially if there are many employees.

Test Script

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement