// conditional reference

SQL XOR operator

True when exactly one of the two operands is true.

Category
Conditional
Returns
boolean
In this category
13 of 43

Syntax

a XOR b | a <> b | (cond1) <> (cond2)

Engine support

EngineSupportNotes
SQL Server Not built in no logical XOR and conditions are not values; compare two CASE expressions. ^ is bitwise
PostgreSQL Not built in no XOR keyword; a <> b on boolean values
MySQL Yes logical operator between two conditions
SQLite Not built in no XOR keyword; (cond1) <> (cond2), since comparisons yield 0/1
Oracle Not built in 23ai+: (cond1) <> (cond2) over BOOLEAN; older releases need CASE

Examples

MySQL

SELECT 1 XOR 1 AS f, 1 XOR 0 AS t, NULL XOR 1 AS n;

PostgreSQL

SELECT true <> false AS t, true <> true AS f, NULL::bool <> true AS n;

SQL Server

SELECT * FROM t WHERE CASE WHEN a = 1 THEN 1 ELSE 0 END <> CASE WHEN b = 1 THEN 1 ELSE 0 END;

Good to know

  • NULL propagates: NULL XOR anything is NULL, so a row with an unknown flag silently drops out of WHERE.
  • Chained XOR in MySQL counts parity: a XOR b XOR c is true when an odd number of operands is true, not 'exactly one'.
  • For booleans, a <> b is XOR whenever both sides are non-NULL. IS DISTINCT FROM never returns NULL, but it treats NULL as a third value (NULL IS DISTINCT FROM false is true), so it is not XOR on unknowns.
  • Bitwise ^ (T-SQL, MySQL) and # (PostgreSQL) are not logical XOR: they work on integers bit by bit, so 6 ^ 3 is 5, not true.

Questions about XOR

What is the XOR truth table?

1 XOR 0 = 1, 0 XOR 1 = 1, 0 XOR 0 = 0, 1 XOR 1 = 0, and any NULL operand makes the whole thing NULL.

How do I write XOR in SQL Server?

T-SQL cannot compare two conditions directly, so turn each into 0/1 with CASE and compare those: CASE WHEN a = 1 THEN 1 ELSE 0 END <> CASE WHEN b = 1 THEN 1 ELSE 0 END. That form also treats NULL as false.

Does a XOR b XOR c mean exactly one is true?

No, it is parity: true when an odd number of the operands is true.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: MySQL.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.