how to check the 3rd max salary from an employee table? One
of the queries used is as follows:

select sal from emp a where 3=(select
count(distinct(sal)) from emp b
where a.sal<=b.sal).

Here in the sub query "select
count(distinct(sal)) from emp b
where a.sal<=b.sal" or
"select count(distinct(sal)) from emp b
where a.sal=b.sal" should reveal the same number of rows is
in't it? Can any one here please explain me how is this
query working perfectly.

However, there is another query to get the 3rd highest of
salaries of employees that logic I can understand. Pls find
the query below.
"select min(salary) from emp where salary in(select
distinct
top 3 salary from
emp order by salary desc)"

Please explain me how

"select sal from emp a where 3=(select
count(distinct(sal)) from emp b
where a.sal<=b.sal)" works

source:http://www.allinterview.com/showanswers/33264.html.

Thanks in advance
Regards,
Karthik.

Answer Posted / gaurav

If you use "select count(distinct(sal)) from emp b
where a.sal=b.sal" It will always give output as 1. because for every salary in emp a, there will be one distinct sal in emp b.

So when we use a.sal <= b.sal, we are counting the number of people who have salary greater than or equal to your salary. So comparing it with 3 will give us 3rd maximum salary.

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are properties of the transaction?

554


What is the difference between execution of triggers and stored procedures?

548


What is integrity in sql?

557


Does normalization improve performance?

552


what is denormalization. : Sql dba

540






What are the properties of a transaction?

559


Can we use views in stored procedure?

511


What is sharding in sql?

562


How can you know that statistics should be updated?

601


What are secondary keys?

557


what is try_catch block in procedure

1189


What are different clauses used in sql?

583


Is a foreign key always unique?

530


What are primary key and foreign key and how they work?

547


Why function is used in sql?

518