Showing posts with label Find nth highest and lowest salary of an Employee. Show all posts
Showing posts with label Find nth highest and lowest salary of an Employee. Show all posts

Thursday, August 4, 2016

Find nth highest and lowest salary of an Employee

This question has been asked many times in interview to candidate that find or fetch nth highest and lowest salary of an Employee like 2nd, 3rd, 4th, 5th… highest and lowest salary of an Employee from Employee table. This question some times also asked as get nth highest and lowest salary of an Employee without using TOP and sub query. Let’s see solutions for all this questions in this article.
Suppose we have following table of Employee with Name and Salary of Employee.
Query to get nth(3rd) highest salary of an Employee
Suppose we want to get 3rd highest salary of an Employee so query should be like.
Let me illustrate above query as here we want to fetch nth(3rd) highest salary of an Employee so first inside sub query we find all top n(3) distinct records using order by descending which result in to top n(3) records with highest salary and than we fetch top 1 record among all these records with order by ascending which full fill our requirement to find nth(3rd) highest salary of an Employee.

Query to get nth(3rd) lowest salary of an Employee

See here we want to find nth(3rd) lowest salary of an Employee so our logical of fetching data will be reversed so first inside sub query we find all top n(3) distinct records using order by ascending which result in to top n(3) records with lowest salary and than we fetch top 1 record among all these records with order by descending which full fill our requirement to find nth(3rd) lowest salary of an Employee.

Query to get nth(3rd) highest salary of an Employee without using TOP and Sub Query

This question also can twisted to find or fetch nth(3rd) highest salary of an Employee without using TOP and Sub Query so solutions can be using With CTE(Common Table Expressions) as below query.
in above query we find salary in descending order using With CTE(Common Table Expression) than we used RowNum = n(3) which results into nth(3rd) highest salary of an Employee without using TOP and Sub Query.

Query to get nth(3rd) lowest salary of an Employee without using TOP and Sub Query

To find or fetch nth(3rd) lowest salary of an Employee without using TOP and Sub Query so solutions can be using With CTE(Common Table Expressions) as below query.
in above query we find salary in ascending order using With CTE(Common Table Expression) than we used RowNum = n(3) which results into nth(3rd) lowest salary of an Employee without using TOP and Sub Query.