T-SQL XOR Operator

Sql ServerTsqlXor

Sql Server Problem Overview


Is there an XOR operator or equivalent function in SQL Server (T-SQL)?

Sql Server Solutions


Solution 1 - Sql Server

There is a bitwise XOR operator - the caret (^), i.e. for:

SELECT 170 ^ 75

The result is 225.

For logical XOR, use the ANY keyword and NOT ALL, i.e.

WHERE 5 > ANY (SELECT foo) AND NOT (5 > ALL (SELECT foo))

Solution 2 - Sql Server

Using boolean algebra, it is easy to show that:

A xor B = (not A and B) or (A and not B)


A B | f = notA and B | g = A and notB | f or g | A xor B    
----+----------------+----------------+--------+--------    
0 0 | 0              | 0              | 0      | 0    
0 1 | 1              | 0              | 1      | 1    
1 0 | 0              | 1              | 1      | 1    
1 1 | 0              | 0              | 0      | 0

Solution 3 - Sql Server

As clarified in your comment, Spacemoses, you stated an example: WHERE (Note is null) ^ (ID is null). I do not see why you chose to accept any answer given here as answering that. If i needed an xor for that, i think i'd have to use the AND/OR equivalent logic:

WHERE (Note is null and ID is not null) OR (Note is not null and ID is null)

That is equivalent to:

WHERE (Note is null) XOR (ID is null)

when 'XOR' is not available.

Solution 4 - Sql Server

MS SQL only short form (since SQL Server 2012):

1=iif( a=b ,1,0)^iif( c=d ,1,0)

Solution 5 - Sql Server

The xor operator is ^

For example: SELECT A ^ B where A and B are integer category data types.

Solution 6 - Sql Server

Solution 7 - Sql Server

<> is generally a good replacement for XOR wherever it can apply to booleans.

Solution 8 - Sql Server

From your comment: > Example: WHERE (Note is null) ^ (ID is null)

you could probably try:

where
   (case when Note is null then 1 else 0 end)
 <>(case when ID is null then 1 else 0 end)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionses011View Question on Stackoverflow
Solution 1 - Sql ServerNathan RiveraView Answer on Stackoverflow
Solution 2 - Sql ServerAlberto De CaroView Answer on Stackoverflow
Solution 3 - Sql ServerShawn KovacView Answer on Stackoverflow
Solution 4 - Sql ServerwasView Answer on Stackoverflow
Solution 5 - Sql ServerSebiView Answer on Stackoverflow
Solution 6 - Sql ServerSQLMenaceView Answer on Stackoverflow
Solution 7 - Sql ServerDavid LarochetteView Answer on Stackoverflow
Solution 8 - Sql ServerGregor yView Answer on Stackoverflow