Leetcode SQL

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

Note: If there is no second highest salary, then the query should return null.

Hint: The inner select would have “null” value if there is not a second highest salary. For example, there is just one record. And the outer “select” is going to select the previous outcome and name it “SecondHighestSalary”.

Solution:

select
(select distinct(Salary) from Employee
order by Salary desc limit 1 offset 1)
as SecondHighestSalary;

Link

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Isabelle

Isabelle

In love with telling stories with data