what's the difference of 'not in' and 'not exists'?

66 views Asked by At

sql1: select * from t1 where not exists (select a from t2 where t2.a = t1.a);

sql2: select * from t1 where t1.a not in (select a from t2 where t2.a is not null);

I think the sql1 is same as sql2, they will rewrite to anti join, right?

1

There are 1 answers

0
Marco Baldelli On

The two queries will give different results if you have NULL values.

Example in Oracle:

create table t1 (a integer);

insert into t1 (a) values (1);
insert into t1 (a) values (2);
insert into t1 (a) values (null);
commit;

create table t2 (a integer);

insert into t2 (a) values (1);
insert into t2 (a) values (3);
insert into t2 (a) values (null);
commit;

set null "{NULL}"

prompt First Query...

select * from t1 where not exists (select a from t2 where t2.a = t1.a);

prompt Second Query...

select * from t1 where t1.a not in (select a from t2 where t2.a is not null);

Output:

First Query...

         A
----------
         2
{NULL}    

2 rows selected.

Second Query...

         A
----------
         2

1 row selected.