176_Second Highest Salary

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

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

For example, given the above Employee table, the query should return200as the second highest salary. If there is no second highest salary, then the query should returnnull.

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

Solution

# solution 1
SELECT max(Salary) as SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT max(Salary) FROM Employee)

# solution 2: easy to generalize to nth largest
SELECT 
    (SELECT distinct Salary 
    FROM Employee
    ORDER BY Salary DESC
    LIMIT 1 OFFSET 1)  as SecondHighestSalary;

# solution 3: use ifnull()
SELECT IFNULL((SELECT DISTINCT salary 
FROM employee
ORDER BY salary desc
LIMIT 1 OFFSET 1), null) as SecondHighestSalary
;

Note

We use IFNULL(expr1, expr2) to return NULL when there is no second highest salary.

IFNULL(expr1,expr2)

Ifexpr1_is notNULL,IFNULL()returnsexpr1; otherwise it returnsexpr2_.

mysql> SELECT IFNULL(1,0);
        -> 1
mysql> SELECT IFNULL(NULL,10);
        -> 10
mysql> SELECT IFNULL(1/0,10);
        -> 10
mysql> SELECT IFNULL(1/0,'yes');
        -> 'yes'

Last updated