As I can see, you can use them as the same thing in a lot of cases, but you can't forget the details behind them.
Probably you can get the same results applying both NOT IN
and NOT EXISTS
, but you could see differences in query which involve the NULL
value. Because NOT EXISTS
is the only way to obtain those rows with the NULL
value.
You can see it better in this example:
update cars set c_owner = NULL where c_id = BMW03444
Well... Let's try to see if we have any car in stock that has not been sold yet.
select count(*) from cars where c_owner not it (select c_name from customers);
Output:
COUNT(*): 0
Where's the failure? Quite simple. You're not requesting a group of cars whose buyers has not been included in the list. You are simply asking for a car without owner. Anybody, even if he's not in the list. The correct form is:
select count(*)
from cars c1
where not exists (
select c_owner
from customers c2
where c1.c_owner=c2.customer_id
);
COUNT(*): 1
This is because NOT IN
needs specific values to check in. So NULL
values are set as FALSE
and not counted.
NOT EXISTS
checks the non existence of an element in a set, so NULL
values are set as TRUE and are included.