I'm trying to solve the LeetCode problem https://leetcode.com/problems/second-highest-salary/description/; my solution so far (see also http://sqlfiddle.com/#!9/4752cb/1) is:
SELECT Salary AS SecondHighestSalary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1;
The problem is that my solution is failing on the following test case:

In other words, it is simply returning no results rather than returning NULL. How can I make it return NULL if there is no second-highest salary?
Update
Following Return a value if no record is found, I tried to encapsulate the query in a sub-query:
SELECT (SELECT Salary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1) AS SecondHighestSalary;
However, this fails on a different test case in which there are two employees with the same salary:

In this case, we are apparently also supposed to return NULL. How can I adapt the 'closer to a solution' query above to handle this?
Here is a query which finally passes the tests:
SELECT (SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1) AS SecondHighestSalary;
It seems more intuitive than the other solutions, no?
Select another row that returns null, using union all so order is preserved, then return only the first row of that:
SELECT * FROM
(
SELECT Salary AS SecondHighestSalary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1
UNION ALL
SELECT NULL
)
LIMIT 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With