Friday, September 10, 2010

Get nth highest record from table

This is one of the most common questions asked for database related questions in interviews. One solution is there. I feel there can be a better solution(in terms of performance issues) but i feel this one is also acceptable. So here it is :



Select Min(Salary) from tbSalary where Salary In(Select top 3 Salary from tbSalary order by salary desc)



Here, I have fetched the 3rd highest record from the salary table. You can replace "3" with the record number you want to get.

Firstly, the inner query runs and orders the salary column in descending order. Than the inner query selects Top 3 records from the ordered list.

Secondly, the outer query fires and select the minimum salary from the list selected by the inner query, which gives the required record.

And that's it, u get the result....

One more thing, if u have a better solution, than do tell me here.....Happy querying.....

No comments:

Post a Comment