MySQL + SQL · Lesson 1
Nth Highest Salary
The Problem
A very common interview question: find the 2nd, 3rd or Nth highest salary from an employees table.
Using LIMIT and OFFSET
-- 2nd highest salary (N=2, so OFFSET 1)
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;salary
------
50000
Using a Subquery
-- highest salary less than the maximum = 2nd highest
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
Summary
- For the Nth highest:
ORDER BY salary DESC LIMIT 1 OFFSET (N-1). - Use DISTINCT to skip duplicate salaries.