write a query to n-th highest salary.
12803-Jul-2024
Updated on 03-Jul-2024
Home / DeveloperSection / Interviews / write a query to n-th highest salary.
Ravi Vishwakarma
03-Jul-2024To retrieve the n-th highest salary from a SQL Server table, you can use a similar approach to the previous query, but adjust the
ROW_NUMBER()
function and filtering criteria. Here's how you can write a query to get the n-th highest salary: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
equals@N
.@N
is a parameter that you can adjust to retrieve the desired n-th highest salary. In the example above,@N
is set to3
, so it will retrieve the third-highest salary.Adjust the
@N
variable to fetch the n-th highest salary you're interested in from your table. This query will effectively fetch the specified n-th highest salary based on the sorting of theSalary
column in descending order.Read more
Write a query to get the second-highest salary.