Find Second Highest Salary From Table In SQL

I have given a name to my blog as 'Find Second Highest Salary From Table In SQL' because in any interview this question is always asked. Also, according to my personal experience, I have faced many interviews, and the same question is asked in all interviews, so to help freshers, I have decided to write this blog, so let us start.

Create a table named employee as follows



Insert the some record into the table and use the following query to display back the added records

selectfrom employee

The output will be look like as follows..


Write a query to retrieve second highest salary from employee table
select MAX (salary) as Salary from employee
where salary < 
(select MAX (salary) as Salary from employee)
Run the above query the output will be as follows.






From the above example, it's clear that the above query displays the second highest salary from the table. In the above query, the nested query is executed first which retrieves the highest salary, and because of the less than condition in the where clause, the first query compares with the second query and retrieves less than the highest salary that is second.
Summary
I hope this article is useful for all readers. If you have any suggestion regarding this article, then please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode