I sometimes interchanged the use of NOT IN
and NOT EXIST
in my sql queries and both yield the same result. Is the logic behind the NOT EXIST
Both will give you the same results. The NOT EXISTS is a correlated sub-query, it is joined to the main query. In the example below, the NOT EXISTS should perform faster on a large dataset.
Find products without orders.
select *
from Products
where ProductId NOT IN (select ProductId FROM Orders)
select *
from Products
where NOT EXISTS (select 1 FROM Orders WHERE orders.ProductId = Products.Id)