A typical SQL Server interview question is to locate the third wage in a database table of employees. The nth highest pay can be discovered in a variety of methods. All of the following questions will also have answers by the time this article is finished.
- How to use a subquery in SQL Server to discover the nth highest income
- Using a CTE, how to determine the nth highest salary in SQL Server
- Finding the second, third, or fifteenth highest wage
For this demonstration, let's utilize the following Employees table.
It is simple to locate the greatest wage. Simply use the Max() method, as seen below. Select Max(Salary) from Employees Utilize a sub query combined with the Max() method as demonstrated below to obtain the second-highest income. Select Max(Salary) from Employees where Salary < (Select Max(Salary) from Employees)
Using a subquery, locate the nth highest income.
Utilizing CTE, determine the nth highest salary.
Any of the searches listed above can be used to determine the second highest income. Simply substitute 2 for N. Similarly, simply substitute 3 for N to discover the third highest income.
Please Note: You may have noticed that the following query may be used to retrieve the nth highest income on several websites. Only if there are no duplicates will the following query be successful.