Not in VS Exists VS Except
Last updated:
Warning: Review and test in a non-production environment before running.
-- not in
-- if the cust_id column is nullable then null value will return true on the next query !!!!!!!!!!!!!
select * from table where customer_id not in (select cust_id from cust);
-- left join or not exists
left join can be a performance problem.
use not exists it is faster
-- examples
declare @x table(a int);
insert @x values(1),(1),(null);
declare @y table(b int not null);
insert @y values(1),(1),(2),(2);
-- bad use
-- where 1 <> 1 = false
-- where 2 <> null = unknown = false
select b from @y where b not in (select a from @x);
-- best use
select b from @y as y where not exists
(select 1 from @x as x
where x.a = y.b);
-- return distinct values after ordered.
-- performance problem too.
select b from @y
except
select a from @x;