The second-highest salary: Why the simplest SQL query is often the smartest
Source: Dev.to
The problem and sample data
We’re given an employee table:
| id | name | salary | department_id |
|---|---|---|---|
| 1 | Ivan | 1000.1234 | 1 |
| 2 | Anna | 1500.1234 | 1 |
| 3 | Oleg | 2200.1234 | 2 |
| 4 | Maria | 2200.1234 | 2 |
| 5 | David | 2000.5678 | 2 |
Expected result: 2000.5678
Problem statement: Find the second highest distinct salary from the employee table.
Key requirement: Return NULL if fewer than two distinct salaries exist (e.g., all employees earn the same).
This isn’t about the “second row” — it’s about the second highest distinct value.
Three common solutions compared
METHOD 1: MAX() + Subquery
SELECT MAX(salary)
FROM employee
WHERE salary