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
No, they are not the same. The IN function translates to a series of OR statements. Typically this trips people up when they use a subquery in the IN function and that query returns at least one null value. E.g. Col Not In( Select Foo From Bar )
. This compares Col <> Foo
for each row. If one of the values of Foo is null, you get Col <> NULL
and the entire statement returns false resulting in no rows.
Exists simply determines if any rows in the subquery are returned (Not Exists being that no rows can be returned). The Select clause is entirely ignored.
Example:
Create Table Test ( Id int not null )
Insert Test ( 1 )
Insert Test ( 2 )
Insert Test ( 3 )
Create Table Bar ( Foo int null )
Insert Bar ( Null )
Insert Bar ( 1 )
Insert Bar ( 2 )
The following will result in no rows since we are effectively doing the comparison of Not( Id = Null Or Id = 1 Or Id = 2 )
Select Id
From Test
Where Id Not In( Select Foo From Bar )
The following however will return one row
Select Id
From Test
Where Not Exists( Select 1 From Bar Where Foo = Id )
In the above query, I will get Id = 3.