Problem

Table: Employee

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+

id is the primary key column for this table. Each row of this table contains information about the salary of an employee.

Write an SQL query to report the second highest salary from the Employee table. If there is no second highest salary, the query should report null.

The query result format is in the following example.

Examples

Example 1:

Input: Employee table:

+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

Output:

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

Solution

Method 1 - Using Nested Query

select max(Salary) as SecondHighestSalary
from Employee
where Salary < (Select max(Salary) from Employee)

Using max() will return a NULL if the value doesn’t exist. So there is no need to UNION a NULL.

Method 2 - Using TOP Keyword of sybase/sql Server

Code

SQL
SELECT TOP 1 salary FROM ( SELECT TOP 2 salary FROM Employee ORDER BY salary DESC) AS emp ORDER BY salary ASC
Pandas
def second_highest_salary(employee: pd.DataFrame) -> pd.DataFrame:
    sorted_salaries = employee['salary'].sort_values(
        ascending=False
    ).drop_duplicates()
    return pd.DataFrame({
        'SecondHighestSalary': [None if sorted_salaries.size < 2 else sorted_salaries.iloc[1]]
    })

Method 3 - Using Limit Keyword of Mysql

SELECT salary FROM
(SELECT salary FROM employees ORDER BY salary DESC LIMIT 2) AS emp
ORDER BY salary LIMIT 1;

Method 4 - Using Limit and Offset

select (
  select distinct Salary from Employee order by Salary Desc limit 1 offset 1
)as second

Change the number after ‘offset’ gives u n-th highest salary Note, the above query handles null correctly, while this query will not, hence a slightly wrong answer:

select distinct salary as SecondHighestSalary
from Employee
order by salary DESC
limit 1 offset 1;

This is because query 1 as additional select, which results in null for empty resultset. While in query 2, we return empty result set instead of null.