Understanding the given correlated subquery

subquery

I am unable to understand how this correlated subquery works on the relation Student={Sid,Sname,marks}

Select Sname from Student s1
where (select count (*) from Student s2 where s1.marks<=s2.marks)=3

I cannot understand the way in which I should comprehend this query starting from inner query. The count (*) returns the total count of rows in a group but here is it calculating for individual condition satisfied.

Can anyone help in this regard?

Best Answer

zgguy's explanation is very good. It is also illustrated nicely in the execution plan (I have used SSMS2014 to generate one):

execution plan

  • the inner query shows on the second "row"
  • nested loops means that for each row in the outer query, inner input in scanned and matching records are selected
  • filter (=3) is applied on records from previous step