Wednesday 14 June 2017

How to find second highest salary in SQL Server?

In this post, I will explain How to find second highest salary in SQL Server table?
Find the second highest salary is a common interview question for many peoples. There are different ways to get a second highest salary using SQL Query. Here I will explain a few of them with below example.
Example-
Consider below simple table Employee.
Name
Salary
A
100,000.00
B
1,000,000.00
C
40,000.00
D
500,000.00

In the above table, D has the second highest salary. Finding the highest salary using SQL query is very easy.
SELECT MAX(Salary) as salary FROM Employee

We can nest the above query to find the second highest salary.

SELECT MAX(Salary) AS salary
FROM Employee
WHERE Salary < (SELECT MAX(Salary) FROM Employee)

Below is another way to find second highest salary.

SELECT  Salary
FROM    Employee
ORDER BY Salary DESC
OFFSET 1 ROWS FETCH NEXT 1 ROW ONLY


0 comments:

Post a Comment

Please do not enter any spam link in the message box.