HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Symmetric difference operation in Transact-SQL?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
symmetricsqloperationdifferencetransact

Problem

I have always known about the UNION operator in SQL, but only recently discovered that there were other set operators, INTERSECT and EXCEPT. I haven't been able to find an operator that does the fourth big set operator, the symmetric difference (e.g. the opposite of INTERSECT.)

It looks like I can get the desired output by using something like

SELECT Field FROM A UNION SELECT Field FROM B 
EXCEPT
SELECT Field FROM A INTERSECT SELECT Field FROM B


(assuming I got the precedence right), or by doing an anti-full-join:

SELECT A.Field, B.Field
FROM A
FULL JOIN B ON B.Id = A.Id
WHERE B.Id IS NULL OR A.Id IS NULL


But both of those look like rather intensive queries, especially compared to the other three basic set operations. Is there a symmetric difference operation in SQL and I just can't find it in the documentation? Or is there a "canonical" way to implement it in T-SQL?

Solution

All set operators are translated to joins or join-like operators. You can witness that in the query plan.

For that reason the full outer join that you have there is the most efficient you can do. Disregarding, of course, the hopefully rare situation in which the optimizer picks a bad plan and a rewrite happens to perform better by luck. This can always happen.

Context

StackExchange Database Administrators Q#71570, answer score: 3

Revisions (0)

No revisions yet.