not in and not exists compared

Purpose
This example compare not in and not exists.When to use them ?

Time Needed : 10Min.

Preparation

They both are not same when that column can contain null and see other performance implications.

create table big as select * from all_objects;
create table small as select * from
all_objects where rownum < 10;

alter table big modify object_id null;
alter table small modify object_id null;
update small set object_id = null where rownum = 1;
create unique index big_idx on big(object_id);
create unique index small_idx on small(object_id);

analyze table big compute statistics
for table
for all indexes
for all indexed columns;

analyze table small compute statistics
for table
for all indexes
for all indexed columns;

set autotrace traceonly
select * from big
where NOT EXISTS (select null
from small
where small.object_id = big.object_id)

select * from big
where object_id NOT IN ( select object_id
from small )

first returns 16k records and second ‘no rows selected’. Find why different ?

update small set object_id = -1 where object_id is null;
commit;
alter table small modify object_id NOT NULL;
analyze table small compute statistics
for table
for all indexes
for all indexed columns;

Select * from big
where NOT EXISTS (select null
from small
where small.object_id = big.object_id)

Select * from big b0
where object_id IS NOT NULL
and object_id NOT IN ( select object_id
from small )

set antijoin to help this
alter session set always_anti_join = MERGE

Select * from big b1
where object_id is not null
and object_id NOT IN ( select object_id
from small )

alter session set always_anti_join = HASH
hints in query could be MERGE_AJ,HASH_AJ

Select /*+ HASH_AJ */ * from big b2
where object_id is not null
and object_id NOT IN ( select object_id
from small )

Backout Procedure
drop table small;
drop table big;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: