Search This Blog

Tuesday 21 April 2015

EXCEPT VS NOT IN AND INTERSECT VS IN in SQL Server

EXCEPT operator returns all distinct rows from left hand side table which does not exist in right hand side table.

"NOT IN" operator 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

--STEP 1 :-

create table #Table1
(
       NAME varchar(50)
)

create table #Table2
(
       NAME varchar(50)
)

--STEP 2 :-

--INSERT VALUES TO #Table1
insert into #Table1 values ('Name 1')
insert into #Table1 values ('Name 2')
insert into #Table1 values ('Name 3')
insert into #Table1 values ('Name 4')

--INSERT VALUES TO #Table2
insert into #Table2 values ('Name 1')
insert into #Table2 values ('Name 2')

--SELECT QUERY
select * from #Table1
select * from #Table2

-----------EXCEPT VS NOT IN OPERATOR-----------------------------

--STEP 3 :-

--USING EXCEPT OPERATOR
select * from #Table1
except
select * from #Table2

--USING NOT IN OPERATOR
select * from #Table1
where NAME NOT IN(select * from #Table2)

--STEP 4 :-

--INSERT DUBLICATE VALUE IN #Table1
insert into #Table1 values ('Name 3')
insert into #Table1 values ('Name 4')

--SELECT QUERY
select * from #Table1

--STEP 5 :-

--USING EXCEPT OPERATOR
select * from #Table1
except
select * from #Table2

--USING NOT IN OPERATOR
select * from #Table1
where NAME NOT IN(select * from #Table2)

-----------INTERSECT VS IN OPERATOR-----------------------------

INTERSECT operator returns all distinct rows from left hand side table which does exist in right hand side table.

"IN" operator will return all rows from left hand side table which are present in right hand side table but it will not remove duplicate rows from the result

--STEP 6 :-

--USING INTERSECT OPERATOR
select * from #Table1
INTERSECT
select * from #Table2

--USING IN OPERATOR
select * from #Table1
where NAME IN(select * from #Table2)

--STEP 7:-

--INSERT DUBLICATE VALUE IN #Table1
insert into #Table1 values ('Name 1')
insert into #Table1 values ('Name 2')

--SELECT QUERY
select * from #Table1

--STEP 8:-

--USING INTERSECT OPERATOR
select * from #Table1
INTERSECT
select * from #Table2

--USING IN OPERATOR
select * from #Table1
where NAME IN(select * from #Table2)

drop table #Table1,#Table2


No comments:

Post a Comment