Second Highest Salary in MySQL and SQL Server - ASP TANMOY

Latest

Monday 15 May 2017

Second Highest Salary in MySQL and SQL Server



Write a SQL query to get the second highest salary from the Employee table.

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return NULL. You can write SQL query in any of your favorite database e.g. MySQL, Microsoft SQL Server or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database. In fact, there are several ways to find second highest salary and you must know couple of them e.g. in MySQL without using LIMIT keyword, in SQL Server without using TOP and in Oracle without using RANK and ROWNUM. Once you solve the problem, Interviewer will most likely increase the difficulty level by either moving to Nth salary direction or taking away this buit-in utilities.

SELECT MAX(salary) FROM Employee WHERE Salary NOT IN ( SELECT Max(Salary)
 FROM Employee);

This will return 200 in our case.

Here is another solution which uses sub query but instead of IN clause it uses < operator

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


Second Maximum Salary in MySQL using LIMIT



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


 



No comments:

Post a Comment