How to find second highest or maximum salary of Employee in SQL - Interview question

Introduction:
In this section we will write SQL query to get second highest salary of Employee. Before writing query its good to be familiar with schema as well as data in table. Here is the Employee table we will be using this SQL example:

SQL query to find second maximum salary of Employee

How to find second highest or maximum salary of Employee in SQL - Interview question
If you look data, you will find that second maximum salary in this case is 6000 and employee name is Henry. Now let’s see some SQL example to find out this second maximum salary.

Second maximum salary using sub query and IN clause:
Sub queries in SQL are great tool for this kind of scenario, here we first select maximum salary and then another maximum excluding result of subquery.
How to find second highest or maximum salary of Employee in SQL - Interview question
Here is another SQL query to find second highest salary using subquery and < operator instead of IN clause:
How to find second highest or maximum salary of Employee in SQL - Interview question
Both of above SQL example will work on all database including Oracle, MySQL, Sybase and SQL Server as they are written using standard SQL keywords. But sometime you can also use database specific features like TOP keyword of SQL Server or Sybase database to find out second highest salary of Employee.

Second highest salary using TOP keyword of Sybase or SQL Server database:
TOP keyword of Sybase and SQL Server database is used to select top record or row of any result set, by carefully using TOP keyword you can find out second maximum or Nth maximum salary as shown below.
How to find second highest or maximum salary of Employee in SQL - Interview question
Here is what this SQL query is doing : First find out top 2 salary from Employee  table and list them in descending order, Now second highest salary of employee is at top so just take that value. Though you need to keep in mind of using distinct keyword if there are more than one employee with top salary, because in that case same salary will be repeated and TOP 2 may list same salary twice.

Second maximum salary using LIMIT keyword of MYSQL database:
LIMIT keyword of MySQL database is little bit similar with TOP keyword of SQL Server database and allows to take only certain rows from result set. If you look at below SQL example, its very much similar to SQL Server TOP keyword example.
How to find second highest or maximum salary of Employee in SQL - Interview question
That’s on How to find second highest salary of Employee using SQL query.



Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment