PostgreSQL bit_xor() Function

The PostgreSQL bit_xor() function is an aggregate function that performs a “bitwise XOR” operation on all non-null input values.

The bitwise XOR processes two binary numbers of the same length, if the two corresponding binary bits are different, the result value of the bit is 1, otherwise it is 0.

bit_xor() Syntax

Here is the syntax of the PostgreSQL bit_xor() function:

bit_xor(expr)

Typically, we use the bit_xor() function like:

SELECT bit_xor(expr), ...
FROM table_name
[WHERE ...]
[GROUP BY group_expr1, group_expr2, ...];

Parameters

expr

Required. A column name or expression. It accepts a value of type integer or bit.

Return value

The PostgreSQL bit_xor() function returns values ​​of the same type as the input parameters, and it returns the result of performing a “bitwise XOR” operation on all non-null input values.

Note that the bit_xor() function only handles non-null values. That is, null values ​​are ignored by the bit_xor() function.

bit_xor() Examples

To demonstrate usages of the PostgreSQL bit_xor() function, we simulate a temporary table using the following statement with UNION and SELECT:

SELECT 4 x
UNION
SELECT 5 x
UNION
SELECT 6 x;
 x
---
 4
 6
 5
(3 rows)

The following statement performs the bit_xor() operation to the values of the x column:

SELECT bit_xor(x)
FROM (
    SELECT 4 x
    UNION
    SELECT 5 x
    UNION
    SELECT 6 x
  ) t;
 bit_xor
--------
      7
(1 rows)

Here, the function bit_xor() performs the “bitwise XOR” operation on the values ​​(4, 5, 6) in the x column, and the calculation steps are as follows:

       4 -> 100
       5 -> 101
       6 -> 110
bit_xor() = 111 = 7

So the bit_xor() function returns 7.