The second-highest salary: Why the simplest SQL query is often the smartest

Published: (January 13, 2026 at 04:51 AM EST)
1 min read
Source: Dev.to

Source: Dev.to

The problem and sample data

We’re given an employee table:

idnamesalarydepartment_id
1Ivan1000.12341
2Anna1500.12341
3Oleg2200.12342
4Maria2200.12342
5David2000.56782

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
Back to Blog

Related posts

Read more »

How To Solve LeetCode 1193

Problem Description The table Transactions has the following columns: - id primary key - country - state enumeration: 'approved' or 'declined' - amount - trans...

How To Solve LeetCode 586

Problem Overview The task is to identify the customer number that has placed the largest quantity of orders. The Orders table contains two identifier columns:...

Database Transaction Leak

Introduction We often talk about memory leaks, but there is another silent performance killer in backend development: Database Transaction Leaks. I recently sp...