Second Highest and Lowest Salary using SQL Query
Nowadays, The question "Find the second highest salary of the employee" becomes very popular. We can find the solution of Highest and Lowest salary of the table.
Let us consider the following table
Employee
Name Salary
Nathan 5000
Ramesh 10000
Sekar 15000
Ram 3000
Kannan 6000
We can get 1st,2nd,3rd,4th.. highest salary of the employee by using the following query. The following query is used to find the second highest salary of the table "Employee"
By replacing the "Select top 2 " into "Select top 3" we can get 3rd highest salary of the table "Employee"..
select top 1 * from Employee where Salary in (select top 2 Salary from Employee order by Salary desc)
Out put of the above query will be as follows
Name Salary
Ramesh 10000
We can get 1st,2nd,3rd,4th.. lowest salary of the employee by using the following query. The following query is used to find the second lowest salary of the table "Employee"
By replacing the "Select top 2 " into "Select top 3" we can get 3rd lowest salary of the table "Employee"..
select top 1 * from Employee where Salary in (select top 2 Salary from Employee order by Salary ) order by Salary desc
Out put of the above query will be as follows
Name Salary
Nathan 5000
Thanks
Nathan
Correlated sub queries are more generalized to find n'th highest or nth lowest salary.
To find nth highest salary
SELECT * FROM Employee E1 WHERE n-1 =
(SELECT COUNT(DISTINCT Salary) FROM Employee E2 WHERE E1.Salary < E2.Salary)
To find 2nd highest salary
SELECT * FROM Employee E1 WHERE 1 =
(SELECT COUNT(DISTINCT Salary) FROM Employee E2 WHERE E1.Salary < E2.Salary)
To find 2nd lowest salary
SELECT * FROM Employee E1 WHERE 1 =
(SELECT COUNT(DISTINCT Salary) FROM Employee E2 WHERE E1.Salary > E2.Salary)
To find nth lowest salary
SELECT * FROM Employee E1 WHERE n-1 =
(SELECT COUNT(DISTINCT Salary) FROM Employee E2 WHERE E1.Salary > E2.Salary)