Question

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

+----+--------+
| 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.

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

SQL Schema

Create table If Not Exists Employee (Id int, Salary int)
Truncate table Employee
insert into Employee (Id, Salary) values ('1', '100')
insert into Employee (Id, Salary) values ('2', '200')
insert into Employee (Id, Salary) values ('3', '300')

My Interesting Code

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

My Perspective

This question is also simple. If you want to find the second highest salary, you can find the highest salary first. Then you can traverse the whole table again, but you need to make all the value are less than the highest salary (regardless of equality). Finally, the maximum of these numbers is the answer.

By the way, if you use “max” function, the column name is “max(Salary)”. You can use “as” to address this problem.