Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the nth highest value in a column and null if it doesn't exist

Tags:

mysql

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:

enter image description here

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:

enter image description here

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?

like image 557
Kurt Peek Avatar asked Oct 24 '25 08:10

Kurt Peek


2 Answers

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?

like image 166
Kurt Peek Avatar answered Oct 26 '25 23:10

Kurt Peek


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
like image 37
Bohemian Avatar answered Oct 26 '25 21:10

Bohemian