Which of these queries is the faster?
NOT EXISTS:
SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE NOT EXISTS (
SELECT 1
FROM
In your specific example they are the same, because the optimizer has figured out what you are trying to do is the same in both examples. But it is possible that in non-trivial examples the optimizer may not do this, and in that case there are reasons to prefer one to other on occasion.
NOT IN
should be preferred if you are testing multiple rows in your outer select. The subquery inside the NOT IN
statement can be evaluated at the beginning of the execution, and the temporary table can be checked against each value in the outer select, rather than re-running the subselect every time as would be required with the NOT EXISTS
statement.
If the subquery must be correlated with the outer select, then NOT EXISTS
may be preferable, since the optimizer may discover a simplification that prevents the creation of any temporary tables to perform the same function.