SQL Query

SQL Query to Get Second Highest Value

Find the second highest salary or value using subquery or LIMIT OFFSET.

SQL Query to Get Second Highest Value

Find the second highest salary or value using subquery or LIMIT 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. LIMIT 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);

Limit Offset

SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 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:

Related Content

From Our Blog

Try it yourself

Practice this query in our interactive SQL sandbox.