Search This Blog

Wednesday, March 20, 2013

EXCEPT and INTERSECT SQL Server

SQL Server > Operators > EXCEPT AND INTERSECT

EXCEPT returns any distinct rows from the left query that are not also found on the right query.
INTERSECT returns any distinct rows that are returned by both the query on the left and right.

Example

 create table #t(name varchar(50))
insert into #t(name) values ('1')
insert into #t(name) values ('2')
insert into #t(name) values ('3')

create table #t1(name varchar(50))
insert into #t1(name) values ('1')
insert into #t1(name) values ('2')
insert into #t1(name) values ('5')

select * from #t
except
select * from #t1

--Result:
--name
--3

select * from #t
intersect
select * from #t1

--Result:
--name
--1
--2

drop table  #t
drop table  #t1