Write SQL query to get the second highest salary among all Employees?

Given a Employee Table with two columns
ID, Salary
10, 2000
11, 5000
12, 3000

Answer:

There are multiple ways to get the second highest salary among all Employees.

  • Option 1: Use SubquerySELECT MAX(Salary)
    FROM Employee
    WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee );In this approach, we are getting the maximum salary in a subquery and then excluding this from the rest of the resultset.
  • Option 2: Use Not equalsselect MAX(Salary) from Employee
    WHERE Salary <> (select MAX(Salary) from Employee )

    This is same as option 1 but we are using <> instead of NOT IN.

Read the full book at www.amazon.com
Posted in SQL, SQL Interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *

*