Friday, March 18, 2016

How to select the nth row in a SQL database table?

A very good interview question is "Write query to find nth top salary of a department.". Now, you would be thinking about how to resolve it without using TOP keyword using SQL Server.

I tried it and found a kind of solution. Keep in mind there could be different solutions for this but the one I am giving here is by using ROW_NUMBER() function.

So here we go:

Salary Table:

 

Queries:

Ordering salary in ascending order.



Taking out 5th row out of the result of above query:








As you can see it is very easy to get nth record by just using ROW_NUMBER() function.