Nth Highest Salary
Medium
SQLWindow
Problem
Schema: Employee(id INT, salary INT).
Write a query that returns the Nth highest distinct salary as column NthHighestSalary. Return NULL if there isn't one.
Example 1
Input: salaries [10, 20, 30], N = 2
Output: 20
Example 2
Input: salaries [10], N = 2
Output: NULL
Constraints
- 1 ≤ N. Treat N as a query parameter
:n.
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 (SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET 1) AS NthHighestSalary;
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 Nth Highest Salary interactively → ← All solutions