// aggregates reference

SQL BIT_XOR function

XORs the values of a group together bit by bit.

Category
Aggregates
Returns
integer
In this category
43 of 52

Syntax

BIT_XOR(x) | BIT_XOR_AGG(x)

Engine support

EngineSupportNotes
SQL Server Not built in No built-in equivalent.
PostgreSQL Yes PostgreSQL 14+ aggregate; # is the scalar XOR operator
MySQL Yes empty or all-NULL group returns 0
SQLite Not built in No built-in equivalent.
Oracle Different name or syntax 21c+: BIT_XOR_AGG; empty or all-NULL group returns 0

Examples

MySQL

SELECT BIT_XOR(id) FROM nodes;

Oracle

SELECT BIT_XOR_AGG(checksum) FROM chunks;

Good to know

  • XOR is self-inverse: any value that appears an even number of times cancels out, which powers parity checks and find-the-odd-one-out tricks.
  • MySQL and Oracle return 0 for empty and all-NULL groups, the XOR identity; PostgreSQL returns NULL.
  • NULLs are skipped.

Questions about BIT_XOR

What is BIT_XOR good for?

Parity checks, cheap checksums and the classic 'every id appears twice, find the odd one' puzzle: XOR all ids.

What does an empty group return?

0 in MySQL and Oracle, NULL in PostgreSQL.

Why does XOR-ing twice cancel?

x XOR x = 0, so feeding the same values again restores the identity.

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: PostgreSQL, MySQL, Oracle.

// 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.