Second Highest Salary
MediumLeetCodeSQL: Subqueries & CTEs
Hint and exampleShowHide
Take the largest value that is strictly smaller than the overall maximum; MAX over no rows gives NULL, which handles the case where no second value exists.
Example: runs(player, score)
player | score
A | 90
B | 75
C | 90
D | 60
SELECT MAX(score) AS second_best
FROM runs
WHERE score < (SELECT MAX(score) FROM runs); -- returns 75
-- if every score were 90, the result would be NULL
More in SQL: Subqueries & CTEs
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | Customers Who Never Order | LeetCode | Easy | Solve Customers Who Never Order on LeetCode (opens in a new tab) | |||
| 2 | Second Highest Salary | LeetCode | Medium | Solve Second Highest Salary on LeetCode (opens in a new tab) | |||
| 3 | Department Highest Salary | LeetCode | Medium | Solve Department Highest Salary on LeetCode (opens in a new tab) | |||
| 4 | Customers Who Bought All Products | LeetCode | Medium | Solve Customers Who Bought All Products on LeetCode (opens in a new tab) | |||
| 5 | Investments in 2016 | LeetCode | Medium | Solve Investments in 2016 on LeetCode (opens in a new tab) |