Can any one explain the below query for getting the 3 maximum salaries?
select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where a.sal <= b.sal) order by a.sal desc;
Someone suuggested to me the use of the above query to get 3 max. salaries in a table. I didn’t understand what is happening in the below part of the query:
3>= (select count(distinct sal) from emp b where a.sal <= b.sal) ;
Can anyone explain it? if there is any other way to get the same result,please advice me with query
Advertisement
Answer
empid sal =============== 1 300 2 50 3 400 4 200 5 150 ================ select distinct sal from emp a where 3 --outer query >= (select count(distinct sal) from emp b --inner query(correlated) where a.sal <= b.sal) order by a.sal desc;
This query fetches all the records from the outer query i.e emp
a
and iterates them one by one, passing value to the inner query.
Let’s take an example:
- It fetches 1st row, which is
1, 300
and passes this value to the inner query - The inner query tries to find a distinct
sal
value that is less than or equal to the records inemp
tableb
- The count is 3, because
50
,200
,150
are less than300
. Since3 >= 3
(inner query result) the answer istrue
and300
is selected. - Now the outer loop counter comes to 2nd row i.e
2, 50
. It passes value to the inner query, in this case count does not satisfy3 >=
criteria, hence50
is not selected. - Now
400
, in this case inner query returns4
and hence it satisfies the criteria, hence400
is selected - Now
200
, in this case inner query returns3
,hence this is also selected - Now
150
, in this case inner query returns2
, hence this has been filtered out - Hence the result will be
400
,300
,200
is selected.