Problem Description
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.
Examples
Example 1:
Input: Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+ Output: +---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+
Example 2:
Input: Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | +----+--------+ Output: +---------------------+ | SecondHighestSalary | +---------------------+ | null | +---------------------+
SQL Solution
SELECT MAX(salary) AS SecondHighestSalary
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee);
Alternative Solution:
SELECT IFNULL(
(SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1),
NULL
) AS SecondHighestSalary;
Solution Explanation
This problem can be solved in two ways:
- First approach:
- Use subquery to find max salary
- Find max salary less than the highest
- Simple but may return empty result
- Second approach:
- Order by salary descending
- Use LIMIT and OFFSET
- Handle NULL with IFNULL
Key points:
- Handle NULL case
- Handle duplicates
- Consider empty table
- Consider single row