sqlsql-servert-sql

Get second highest salary, return null if no second highest


Null must be returned if:
- There are less than 2 rows in table
- There isn't a second highest salary because everyone has the same salary

Everything I look up seems to be aimed towards older versions of Sql Server

DECLARE @find int = (Select COUNT(*) from Employee);

IF (@find = 1)
    select null as 'SecondHighest'
else
    select Salary as 'SecondHighest' 
    from Employee
    order by Salary desc
    offset 1 rows fetch next 1 rows only;

I have managed to return null if there is less than 2 columns, although I think there may be a better way to do this. However, I can't fix the second problem:
"There isn't a second highest salary because everyone has the same salary"


Solution

  • Here's a similar approach to @alx (which was nice and simple btw, so +1) but it will be easier to generalise to pick the nth highest salary:

    SELECT MAX(Salary)
    FROM
    (
      SELECT Salary, DENSE_RANK() OVER(ORDER BY Salary DESC) AS Rank
      FROM Employee
    ) E
    WHERE (Rank = 2);