Skip to content
Advertisement

Explanation of the query for getting the 3 maximum salaries

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:

  1. It fetches 1st row, which is 1, 300 and passes this value to the inner query
  2. The inner query tries to find a distinct sal value that is less than or equal to the records in emp table b
  3. The count is 3, because 50, 200, 150 are less than 300. Since 3 >= 3 (inner query result) the answer is true and 300 is selected.
  4. 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 satisfy 3 >= criteria, hence 50 is not selected.
  5. Now 400, in this case inner query returns 4 and hence it satisfies the criteria, hence 400 is selected
  6. Now 200, in this case inner query returns 3,hence this is also selected
  7. Now 150, in this case inner query returns 2, hence this has been filtered out
  8. Hence the result will be 400, 300, 200 is selected.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement