To 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:
SELECT TOP 1 Salary
FROM (
SELECT Salary, ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum
FROM YourTableName
) AS SalaryRanked
WHERE RowNum = 2;
In this query:
Inner Query (SalaryRanked): This subquery selects the
Salary column from your table (YourTableName) and assigns a row number (RowNum) to each row based on the descending order of
Salary.
Outer Query: The outer query selects the Salary from the
SalaryRanked subquery where the RowNum equals 2, which corresponds to the second-highest salary.
Make sure to replace YourTableName with the actual name of your table and
Salary 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
Select TOP 1 *
from (
select *, ROW_NUMBER() OVER(order by Salary Desc ) As RNO
from Employees
) As EMP
where EMP.RNO = 2
OR
select top 1 * from Employees
where Salary < (select MAX(Salary) As Salary from Employees)
order by Salary Desc
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To 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 theSalarycolumn 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
Salaryfrom theSalaryRankedsubquery where theRowNumequals2, which corresponds to the second-highest salary.Make sure to replace
YourTableNamewith the actual name of your table andSalarywith 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