SQL Interview Questions
In this article, I will share my SQL interview experience with questions and Answers.
1. How to find the Nth highest salary from a table
Finding the Nth highest salary in a table is the most common question asked in interviews.
Here is the list of ways to do this....
To find the highest salary it is straight forward. We can simply use the Max() function as shown below.
Select Max(Salary) from Employees
To get the second highest salary use a sub query along with Max() function as shown below.
Select Max(Salary) from Employees where Salary < (Select Max(Salary) from Employees)
A. To find nth highest salary using Sub-Query
B. To find nth highest salary using CTE
I hope this post will help you. Please put your feedback using comments which will help me to improve myself for the next post. If you have any doubts or queries, please ask in the comments section and if you like this post, please share it with your friends. Thanks!
In this article, I will share my SQL interview experience with questions and Answers.
1. How to find the Nth highest salary from a table
Finding the Nth highest salary in a table is the most common question asked in interviews.
Here is the list of ways to do this....
To find the highest salary it is straight forward. We can simply use the Max() function as shown below.
Select Max(Salary) from Employees
To get the second highest salary use a sub query along with Max() function as shown below.
Select Max(Salary) from Employees where Salary < (Select Max(Salary) from Employees)
A. To find nth highest salary using Sub-Query
SELECT TOP 1 SALARY FROM ( SELECT DISTINCT TOP N SALARY FROM EMPLOYEES ORDER BY SALARY DESC ) RESULT ORDER BY SALARY
B. To find nth highest salary using CTE
WITH RESULT AS ( SELECT SALARY, DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSERANK FROM EMPLOYEES ) SELECT TOP 1 SALARY FROM RESULT WHERE DENSERANK = N
I hope this post will help you. Please put your feedback using comments which will help me to improve myself for the next post. If you have any doubts or queries, please ask in the comments section and if you like this post, please share it with your friends. Thanks!
0 Comments