Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL equivalent of relational algebra DIVISION

Here is an example T(A) = RENTED(A,C) / BOATS(C)

select distinct R1.A from RENTED R1  
where not exists                     
  (select * from SAILBOAT S     
   where not exists                  
     (select * from RENTED R2        
      where R1.A = R2.A              
        and R2.C = S.C)              
   );

My question is, if NOT EXISTS just returns TRUE or FALSE, how does SELECT distinct R1.A know which values to return?

For example this jsfiddle

This query returns EVERYTHING in the numbers column if there exists a number = 5

like image 390
Instinct Avatar asked Oct 30 '13 22:10

Instinct


1 Answers

As wildplasser and sqlvogel have mentioned, the subquery gets executed once for each row in the outer query.

The result of the subquery (TRUE / FALSE) determines whether the row in the outer query would be returned. Invariably, the parent key (identifier) columns of the outer query would be referenced within the subquery to check its existence in other tables. This reference makes the subquery a "correlated subquery".

Please see the updated fiddle.

like image 165
Joseph B Avatar answered Oct 21 '22 21:10

Joseph B