This guide is specifically for SQL Server syntax.
How to Get Second Highest Value in SQL
Find the second highest salary or value using subquery or TOP OFFSET.
Quick Answer
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
Explanation
The subquery approach finds the max excluding the actual max. TOP OFFSET skips the first result. DENSE_RANK handles ties correctly.
Query Variants
Subquery
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees);
TOP Offset
SELECT DISTINCT salary FROM employees ORDER BY salary DESC TOP 1 OFFSET 1;
Nth Highest
SELECT salary FROM ( SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM employees ) ranked WHERE rank = 2;
Pro Tips
- Use DENSE_RANK for handling ties
- DISTINCT prevents duplicate results
- Adjust OFFSET for Nth highest value
Related SQL Queries
Continue learning with more SQL query examples:
SQL Server-Specific Notes
This page covers SQL Server syntax. Other databases may have different syntax for similar operations.