EXISTS
EXISTS
tells you whether a subquery returns at least one row of data.Suppose you want a list of farmers who are also landowners.You could get one like this:
SELECT Farmer FROM Farms WHERE EXISTS
(SELECT * FROM Landowners
WHERE Landowners.Name = Farms.Farmer)
This query returns the names of all farmers who also figure in the Landowners table.The EXISTS
predicate returns true
if the result set of the subselect contains at least one row.If it is empty, EXISTS
returns false
. EXISTS
never returns NULL
, because a result set always either has rows, or hasn’t.Of course the subselect’s search condition may evolve to NULL
for certain rows, but that doesn’t cause any uncertainty: such a row won’t be included in the subresult set.
Note
|
In reality, the subselect doesn’t return a result set at all.The engine simply steps through the Landowners records one by one and applies the search condition.If it evaluates to |
NOT EXISTS
always returns the opposite of EXISTS
: false
or true
, never NULL
.NOT EXISTS
returns false
immediately if it gets a true
result on the subquery’s search condition.Before returning true
it must step through the entire set.