What\'s the difference between not in
and not exists
in an Oracle query?
When do I use not in
? And not exist
?
The difference between NOT IN and NOT EXISTS becomes clear where there are NULL
values included in the result.
For example:
create table test_a (col1 varchar2(30 char));
create table test_b (col1 varchar2(30 char));
insert into test_a (col1) values ('a');
insert into test_a (col1) values ('b');
insert into test_a (col1) values ('c');
insert into test_a (col1) values ('d');
insert into test_a (col1) values ('e');
insert into test_b (col1) values ('a');
insert into test_b (col1) values ('b');
insert into test_b (col1) values ('c');
insert into test_b (col1) values (null);
Note: They key difference is that test_b
contains a null
value.
select * from test_a where col1 not in (select col1 from test_b);
No rows returned
select * from test_a where
not exists
(select 1 from test_b where test_b.col1 = test_a.col1);
Returns
col1
====
d
e