Can anyone explain this query when 2= subquery is referenced. How does SQL think about this
Top 2nd salary:
Select distinct Salary
from Employee e1
where 2=Select count(distinct Salary) from Employee e2 where e1.salary<=e2.salary;
Can anyone explain this query when 2= subquery is referenced. How does SQL think about this
Top 2nd salary:
Select distinct Salary
from Employee e1
where 2=Select count(distinct Salary) from Employee e2 where e1.salary<=e2.salary;
It will find the second highest salary for all employees.
select distinct salary
from employee e1
where 2 = (select count(distinct salary)
from employee e2
where e1.salary <= e2.salary);
It does it by searching all the employees and compares that salary to other employees salary (in the subquery). But the subquery only finds all the salaries that are identical or higher. Then it uses distinct to find unique ones and the 2 = (..)
makes sure there is only 2 different salaries that match. Which would be itself and one higher. That's in the e1.salary <= e2.salary
. e1.salary
is itself.
So if
then the subquery for Bob will find the values 102 and 104, because 102 is identical and 104 is higher, and there are no other higher ones. Since there are exactly 2 distinct salaries count(distinct salary)
, the entire query will return the result from Bob's row. That is 102.
When the row for Emily is evaluated, the subquery will find 100, 102 and 104, because they are all greater or equal to the salary for Emily. But since the count will then be 3, that row is discarded.
Similarly will rows for Peter and Sally be discarded because for those the result of the subquery will be 1.