How can you find the second highest salary from a table?
To find the second highest salary from a table in SQL, there are multiple methods, depending on what your SQL dialect supports. Here are the most common approaches:
✅ Method 1: Using LIMIT
and OFFSET
(MySQL, PostgreSQL)
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
LIMIT 1 OFFSET 1
skips the highest salary and returns the next one.
DISTINCT
ensures no duplicates if multiple employees have the same salary.
✅ Method 2: Using a Subquery with MAX()
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
- This returns the maximum salary that is less than the highest one, i.e., the second highest.
- Works in most SQL dialects (MySQL, PostgreSQL, SQL Server, Oracle, etc.)
✅ Method 3: Using DENSE_RANK()
(SQL Server, PostgreSQL, Oracle)
SELECT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees
) ranked
WHERE rank = 2;
- This handles ties properly — e.g., if two people have the highest salary, the next distinct one is ranked 2nd.
✅ Method 4: Using TOP
with Subquery (SQL Server)
SELECT TOP 1 salary
FROM employees
WHERE salary < (
SELECT MAX(salary) FROM employees
)
ORDER BY salary DESC;
- This is similar to Method 2 but written using SQL Server syntax.
Which One Should You Use?
SQL Version |
Best Method |
MySQL |
Method 1 or 2 |
PostgreSQL |
Method 1, 2, or 3 |
SQL Server |
Method 3 or 4 |
Oracle |
Method 2 or 3 |
Let me know if you want to get the employee(s) with the second highest salary too — I can show that as well.