[SQL] [LeetCode] Challenge log 176

176. Second Highest Salary

Use limit, offset, order by together


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

1
2
3
4
5
6
7
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+

For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

1
2
3
4
5
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+

Soulution:
1
2
3
4
5
select ifnull(
(select distinct salary
from Employee
order by salary desc
limit 1 offset 1), null) as SecondHighestSalary
1
2
3
4
5
6
7
8
-- alter
select max(E.salary) as SecondHighestSalary
from Employee E
where E.salary !=
(
select max(salary) as max
from Employee
)
0%