## 176. Second Highest Salary

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                 |
+---------------------+
```

b'
\n\n

## Solution

\n
\n

#### Approach: Using sub-query and `LIMIT` clause [Accepted]

\n

Algorithm

\n

Sort the distinct salary in descend order and then utilize the `LIMIT` clause to get the second highest salary.

\n
`SELECT DISTINCT\n    Salary AS SecondHighestSalary\nFROM\n    Employee\nORDER BY Salary DESC\nLIMIT 1 OFFSET 1\n`
\n

However, this solution will be judged as \'Wrong Answer\' if there is no such second highest salary since there might be only one record in this table. To overcome this issue, we can take this as a temp table.

\n

MySQL

\n
`SELECT\n    (SELECT DISTINCT\n            Salary\n        FROM\n            Employee\n        ORDER BY Salary DESC\n        LIMIT 1 OFFSET 1) AS SecondHighestSalary\n;\n`
\n

#### Approach: Using `IFNULL` and `LIMIT` clause [Accepted]

\n

Another way to solve the \'NULL\' problem is to use `IFNULL` funtion as below.

\n

MySQL

\n
`SELECT\n    IFNULL(\n      (SELECT DISTINCT Salary\n       FROM Employee\n       ORDER BY Salary DESC\n        LIMIT 1 OFFSET 1),\n    NULL) AS SecondHighestSalary\n`
\n
'