How do SQL EXISTS statements work?

Think of it this way:

For ‘each’ row from Suppliers, check if there ‘exists’ a row in the Order table that meets the condition Suppliers.supplier_id (this comes from Outer query current ‘row’) = Orders.supplier_id. When you find the first matching row, stop right there – the WHERE EXISTS has been satisfied.

The magic link between the outer query and the subquery lies in the fact that Supplier_id gets passed from the outer query to the subquery for each row evaluated.

Or, to put it another way, the subquery is executed for each table row of the outer query.

It is NOT like the subquery is executed on the whole and gets the ‘true/false’ and then tries to match this ‘true/false’ condition with outer query.

Leave a Comment