Easy

注意筛选结果可能为null, 要对null进行处理

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

Approach1

Using sub-query and LIMIT clause [Accepted]
Algorithm
Sort the distinct salary in descend order and then utilize the LIMIT clause to get the second highest salary.

  1. SELECT DISTINCT
  2. Salary AS SecondHighestSalary
  3. FROM
  4. Employee
  5. ORDER BY Salary DESC
  6. LIMIT 1 OFFSET 1

However, this solution will be judged as ‘Wrong Answer’ if there is no such second highest salary since there might be only one record in this table. To overcome this issue, we can take this as a temp table.
MySQL

  1. SELECT
  2. (SELECT DISTINCT
  3. Salary
  4. FROM
  5. Employee
  6. ORDER BY Salary DESC
  7. LIMIT 1 OFFSET 1) AS SecondHighestSalary
  8. ;

Approach2

Using IFNULL and LIMIT clause [Accepted]
Another way to solve the ‘NULL’ problem is to use IFNULL funtion as below.
MySQL

  1. SELECT
  2. IFNULL(
  3. (SELECT DISTINCT Salary
  4. FROM Employee
  5. ORDER BY Salary DESC
  6. LIMIT 1 OFFSET 1),
  7. NULL) AS SecondHighestSalary