November 20, 2003 07:20 PM

Set-Operation Alternatives

How to mimic INTERSECT and EXCEPT in T-SQL
Rating: (0)
SQL Server Magazine
InstantDoc ID #40321
ANSI SQL defines three operations—UNION, INTERSECT, and EXCEPT—that you can apply to two sets. These operations let you combine rows from different sets, locate which rows exist in both input sets, or find which rows exist in one set but not the other. Each of these operations has many uses and practical implementations. For example, you can use UNION to combine sales data from partitioned tables, INTERSECT to find which customers are also employees, and EXCEPT to find which customers aren't employees. However, T-SQL supports only the UNION operation. Fortunately, you have alternatives in T-SQL that you can use to provide the functionality of the missing operations.

...This article is for paid Professional Members only.

Already a Professional Member? Please log in now:

NOT A PROFESSIONAL MEMBER? YOU CHOOSE:

Professional Membership

Monthly

Annual

VIP Membership

Monthly

Annual

Add a Comment

To mohanit,

Basically, you need to perform the INTERSECT operation between each two pairs independently. Create a derived table / view out of the result table, and then perform a similar operation between that table expression and the third table and so on.
You know that SQL Server 2005 will support native INTERSECT and EXCEPT set operations. Unfortunately, only the DISTINCT option and not yet the ALL one.

To Alejandro I appreciate the correction.

Thanks for your comments,
Itzik Ben-Gan


BG_SQL 5/17/2005 9:28:46 PM


I got a question...how would the intersection work if we had more than 2 sets of records...ie
u, v, x, y, z

U {('R1',1) , ('R2',2)}
V {('R2',2) , ('R4',4)}
X {('R1',1) , ('R2',2)}
Y {('R4',4) , ('R2',2)}
Z {('R3',3) , ('R2',2)}

The Intersection query in Listing 3 will give
'R1',1
'R2',2
'R4',4

The correct answer is 'R2',2...could you let me know how to handle this pblm...

MOHAN5/3/2005 11:32:28 AM


Outstanding article, as all articles from sqlmag.

Small correction, the result from V EXCEPT U is {3, 4}

and another solution for "except distinct" could be:


select
col1,
col2
from
(
select 'u' as cFrom, * from u

union

select 'v', * from v
)a(cFrom, col1, col2)
group by
col1,
col2
having
count(distinct cFrom) = 1 and min(distinct cFrom) = 'v'


Here the union operator is in charge of eliminate duplicates. Just change min(distinct cFrom) = 'u' to have the result for "u except v".


Regards,

Alejandro Mesa

Alejandro Mesa 11/26/2003 7:41:20 AM


You must log on before posting a comment.

Are you a new visitor? Register Here
GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS