Wednesday, May 18, 2022

Writing Query to Find Second Highest Salary in SQL

1) options  1 (without using LIMIT function )

Answer :
SELECT MAX(Salary) From Employee WHERE Salary < ( SELECT Max(Salary) FROM Employee);

2) options  2 (without using LIMIT function )
Answer :

SELECT TOP 1 Salary FROM ( SELECT TOP 2 Salary FROM Employee ORDER BY Salary DESCAS MyTable ORDER BY Salary ASC;


3) options  3 (using LIMIT function )
Answer :

SELECT Salary FROM (SELECT Salary FROM Employee ORDER BY salary DESC LIMIT 2AS Emp ORDER BY salary LIMIT 1;



GENERIC  SOLUTION USING DENSE_RANK  

select * from(select ename, salary, dense_rank() over(order by salary desc)r from Emp) where r=2


change the r=3 for  3RD Highest salary 
                   r=4 for  4 th  Highest salary ,,, and so on

No comments:

Post a Comment

Stored Procedure

  What is a Stored Procedure ? A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again. S...