Write a query to get the second-highest salary.
15503-Jul-2024
Updated on 03-Jul-2024
Home / DeveloperSection / Interviews / Write a query to get the second-highest salary.
Ravi Vishwakarma
03-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.Read more
Write a basic SELECT statement to retrieve data from a SQL Server table.