176. Second Highest Salary
SQL 50 · Advanced String Functions, Regex, Clause (day 7). Decode it with the hints, solve it on LeetCode, then compare with the reference solution in MySQLPostgreSQL.
Your work
Hints
Open one at a time. Try to finish with as few as you can.
1. What does one output row represent?
One value, or NULL.
2. Approach
SELECT (SELECT DISTINCT salary … ORDER BY salary DESC LIMIT 1 OFFSET 1) AS SecondHighestSalary.
3. The trap
Without the outer SELECT, an empty result returns no rows instead of NULL.
Reference solution
Tested on MySQL 8.0 and PostgreSQL 16. Switch dialect at the top of the page.
Show the MySQLPostgreSQL solution
SELECT (
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1
) AS SecondHighestSalary;