We can also use the TOP keyword (for databases that support the TOP keyword, like SQL Server) to find the nth highest salary.
SELECT TOP 1 Emp_ID,Emp_Name,Emp_Sal,Location FROM ( SELECT DISTINCT TOP 1 Emp_ID,Emp_Name,Emp_Sal,Location FROM Employee ORDER BY Emp_Sal DESC ) AS Emp ORDER BY Emp_Sal
To understand the query above, first look at the subquery, which simply finds the N highest salaries in the Employee table and arranges them in descending order. Then, the outer query will actually rearrange those values in ascending order, which is what the very last line “ORDER BY Salary” does, because of the fact that theORDER BY Defaultis to sort values in ASCENDING order. Finally, that means the Nth highest salary will be at the top of the list of salaries, which means we just want the first row, which is exactly what “SELECT TOP 1 Salary”
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
We can also use the TOP keyword (for databases that support the TOP keyword, like SQL Server) to find the nth highest salary.
To understand the query above, first look at the subquery, which simply finds the N highest salaries in the Employee table and arranges them in descending order. Then, the outer query will actually rearrange those values in ascending order, which is what the very last line “ORDER BY Salary” does, because of the fact that the ORDER BY Default is to sort values in ASCENDING order. Finally, that means the Nth highest salary will be at the top of the list of salaries, which means we just want the first row, which is exactly what “SELECT TOP 1 Salary”