Skip to content
Advertisement

How can I replace empty value to null with SQL?

Let us say, I want to find the second highest salary. For that I use the following query.

select b.Salary as SecondHighestSalary from 
(
    select Salary, rank() over (order by Salary desc) as r 
    FROM Employee
) b
WHERE b.r = 2;

However, I want this to return null when the table only contains one entry, and therefore there is no 2nd highest salary. How can I do that?

Advertisement

Answer

Use your query with aggregation:

select max(Salary) as SecondHighestSalary 
from (
    select Salary, rank() over (order by Salary desc) as r 
    FROM Employee
) t
where r > 1;

The aggregate function max() will return null in case there is no 2nd highest salary.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement