The Second Highest Salary interview question asks you to query a salary table and return the second-highest distinct salary. If no second-highest salary exists (because there is only one distinct salary or the table is empty), return NULL. This is a classic SQL ranking and null-handling problem that tests multiple approaches: subquery, LIMIT/OFFSET, and window functions.
Apple, Microsoft, Meta, Amazon, Google, Bloomberg, and Adobe ask this SQL problem because ranking and "Nth highest" queries are among the most common in business analytics. Returning NULL when the result doesn't exist (rather than an empty result set) is a nuance that separates careful SQL writers from beginners. This problem directly tests knowledge of DISTINCT, ORDER BY, LIMIT, OFFSET, and the IFNULL/COALESCE pattern.
Multiple approaches work. Subquery approach: select the maximum salary that is less than the overall maximum:
SELECT IFNULL(
(SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET 1),
NULL
) AS SecondHighestSalary;
Window function approach: use DENSE_RANK() to rank salaries, then filter for rank = 2:
SELECT MAX(salary) AS SecondHighestSalary
FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM Employee) t
WHERE rnk = 2;
Employee salaries: [100, 200, 300].
Salaries: [100, 100].
For the Second Highest Salary coding problem, the database window function and subquery interview pattern is essential. Know all three approaches: subquery with LIMIT/OFFSET, nested MAX with exclusion, and DENSE_RANK() window function. Interviewers at Visa and Barclays often ask for the generalized "Nth highest salary" — parameterize your DENSE_RANK solution with a variable N. Practice the IFNULL/COALESCE null-handling pattern, which appears in every "return NULL if not exists" SQL problem.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Managers with at Least 5 Direct Reports | Medium | Solve | |
| Nth Highest Salary | Medium | Solve | |
| Exchange Seats | Medium | Solve | |
| Product Price at a Given Date | Medium | Solve | |
| Monthly Transactions I | Medium | Solve |