176. Second Highest Salary

Description

Write a SQL query to get the second highest salary from the Employee table.

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

My Solution

Source Code

1
2
3
4
5
6
7
8
9
10
11
IF (SELECT COUNT(DISTINCT Salary) FROM Employee) < 2
    SELECT NULL AS 'SecondHighestSalary'
ELSE
    BEGIN
        SELECT DISTINCT Salary 
        AS 'SecondHighestSalary'
        FROM Employee
        ORDER BY Salary DESC
        OFFSET 1 ROW
        FETCH NEXT 1 ROW ONLY
    END

Analysis

This one was easy. We simply select all the unique salaries and sort them so they're in order. Then we just select the one with an offset of 2.

By the way, the OFFSET/FETCH syntax for MS SQL is so overly verbose and super reundant. In mySQL all you need is LIMIT and OFFSET. None of this FETCH FIRST/NEXT x ROW/ROWS stuff. And what's worse is that FIRST/NEXT are literally the same, same with ROW/ROWS.