Explaining a SQL query

Tags:
SQL Server
SQL Server Query
I have a query for finding the fith lowest salary in a SQL database, and I am not able to understand how this query will be processed internally. It is: select * from emp a where 5= (select count(distinct sal) from emp where a.sal>=b.sal) Can you explain this to me?

Answer Wiki

Thanks. We'll let you know when a new response is added.

This is rather clever. I think you were missing a ‘b’

select * from emp a
where 5=
(select count(distinct sal) from emp b <– this was missing?
where a.sal>=b.sal)

Here is how it works .. taking some simple numbers
15 , 12 , 10 ,9 ,7 ,4 ,2

This matches the table with itself with >=

15 – 15 1 match

12 12 and 15 2 matches

10 10, 12, 15 3 matches

9 9, 10, 12, 15 4 matches

7 7,9,10,12,15 5 matches

so it’s made this temp table from the inner match rule and a.sal of 7 has 5 distinct b.sals

Phil

But I think that this can return multiple rows if there’s a tie at the 5th salary

Discuss This Question:  

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

Thanks! We'll email you when relevant content is added and updated.

Following

Share this item with your network: