I am trying to solve Leetcode's second highest salary (https://leetcode.com/problems/second-highest-salary/). Here's what I implemented on postgres:
select foo.salary as "SecondHighestSalary"
from
(select salary,
dense_rank() over (order by salary desc) as rank
from Employee) foo
where rank = 2;
But the issue is, I need to return NULL if there are no records with rank = 2. I then tried
select (case
when count(1) = 0 then NULL
else salary
end
)
from
(select salary,
dense_rank() over (order by salary desc) as rank
from Employee) foo
where rank = 2
group by salary;
But it still returns no records. How do I output NULL when no records are returned?
salarycan be NULL. Given that they ask for a NULL result, that's quite an omission.