Introduction
"EXCEPT
" operator was introduced in SQL SERVER 2005. This operator used to achieve Distinct
and Not In
queries. EXCEPT
operator returns all distinct rows from left hand side table which does not exist in right hand side table.
On the other hand, "NOT IN
" will return all rows from left hand side table which are not present in right hand side table but it will not remove duplicate rows from the result.
Example of EXCEPT
vs NOT IN
in SQL SERVER:
create table #tblsample (ProductId tinyint)
create table #tblsample2 (ProductId tinyint)
insert into #tblsample values (1)
insert into #tblsample values (2)
insert into #tblsample values (3)
insert into #tblsample values (4)
insert into #tblsample2 values (1)
select * from #tblsample
select * from #tblsample2
select * from #tblsample
except
select * from #tblsample2
select * from #tblsample
where productid NOT IN(
select * from #tblsample2)
insert into #tblsample values (1)
insert into #tblsample values (2)
select * from #tblsample
PRINT 'EXCEPT RETURNS DISTINCT VALUES'
select * from #tblsample except select * from #tblsample2
PRINT 'NOT IN RETURNS DUPLICATE VALUES IF ANY'
select * from #tblsample where productid NOT IN(select * from #tblsample2)
select * from #tblsample
except
select productid from #tblsample2
DROP TABLE #tblsample
DROP TABLE #tblsample2