How to Write a Query to Find the Second Highest Salary in SQL Server?
How to Write a Query to Find the Second Highest Salary in SQL Server?
14415-Jul-2024
Updated on 16-Jul-2024
Home / DeveloperSection / Forums / How to Write a Query to Find the Second Highest Salary in SQL Server?
How to Write a Query to Find the Second Highest Salary in SQL Server?
Ravi Vishwakarma
16-Jul-2024To retrieve the second-highest salary from a SQL Server table, you can use a subquery with the
ROW_NUMBER()
function. Here's how you can do it:In this query:
Inner Query (
SalaryRanked
): This subquery selects theSalary
column from your table (YourTableName
) and assigns a row number (RowNum
) to each row based on the descending order ofSalary
.Outer Query: The outer query selects the
Salary
from theSalaryRanked
subquery where theRowNum
equals2
, which corresponds to the second-highest salary.Make sure to replace
YourTableName
with the actual name of your table andSalary
with the actual column name containing the salaries in your database schema. This query will give you the second-highest salary from your table.Example
OR
Read more
Write a basic SELECT statement to retrieve data from a SQL Server table.
Help with Writing a Subquery to Get Aggregate Data in SQL Server
SQL Query to Calculate Running Total in SQL Server