Explaining a SQL 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?

Software/Hardware used:
ASKED: December 29, 2008  7:54 PM
UPDATED: December 29, 2008  10:21 PM

Answer Wiki:
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
Last Wiki Answer Submitted:  December 29, 2008  10:21 pm  by  philpl1jb   44,150 pts.
All Answer Wiki Contributors:  philpl1jb   44,150 pts.
To see all answers submitted to the Answer Wiki: View Answer History.


Discuss This Question:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _