Tuesday 15 May 2012

To Find Second Highest Salary from Employee Table in SQL


Here we are going to find the second highest salary in the Table

Employess:

EmpId
EmpName
Salary
1
sajil
5000
2
vinoth
5865
3
viji
5265
4
Rajiv
20000
5
Mathan
7890

SQL Statement:

SELECT MIN(Salary)

FROM Employees

WHERE EmpID IN

(

SELECT TOP 2 EmpID

FROM Employees

ORDER BY Salary Desc

)



The same query can be re-written using a derived table, as shown below, and it performs twice
as fast as the above query:



SELECT MIN(Salary)
FROM
(
SELECT TOP 2 Salary
FROM Employees
ORDER BY Salary DESC
) AS A

Result LookLike This:


EmpId

EmpName

  Salary
5
Mathan
  7890


No comments:

Post a Comment