Second Highest Salary

Medium SQLSubquery

Problem

Schema: Employee(id INT, salary INT). Return the second-highest distinct salary as column SecondHighestSalary. If there's no second-highest, return NULL.

Example 1 Input: salaries [100, 200, 300] Output: 200
Example 2 Input: salaries [100] Output: NULL
Example 3 Input: salaries [100, 100] Output: NULL

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

SQL

SELECT MAX(salary) AS SecondHighestSalary
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee);

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Second Highest Salary interactively → ← All solutions