Home > Blockchain >  how to use aggregate function bit_xor in postgres
how to use aggregate function bit_xor in postgres

Time:11-09

manual:

bit_xor
Computes the bitwise exclusive OR of all non-null input values. Can be useful as a checksum for an unordered set of values.

I don't understand the explanation.

with cte as (
select 1::bit(4)
union
select 3::bit(4)
union
select 7::bit(4)
union
select 5::bit(4)
)
select *,bit_xor(bit) over()  from cte;

return

 bit  | bit_xor
------ ---------
 0001 | 0000
 0011 | 0000
 0101 | 0000
 0111 | 0000
(4 rows)


with cte as (
select 1::bit(4)
union
select 3::bit(4)
union
select 7::bit(4)
)
select *,bit_xor(bit) over()  from cte;

return

 bit  | bit_xor
------ ---------
 0001 | 0101
 0011 | 0101
 0111 | 0101
(3 rows)

CodePudding user response:

bit_xor should work like this for each digit of the input rows :

With 2 input rows :

1 xor 1 = 0
0 xor 1 = 1
1 xor 0 = 1
0 xor 0 = 0

With 3 input rows :

1 xor (1 xor 1) = 1
1 xor (0 xor 1) = 0
1 xor (1 xor 0) = 0
1 xor (0 xor 0) = 1
0 xor (1 xor 1) = 0
0 xor (0 xor 1) = 1
0 xor (1 xor 0) = 1
0 xor (0 xor 0) = 0

With 4 input rows :

1 xor (1 xor (1 xor 1)) = 0
1 xor (1 xor (0 xor 1)) = 1
1 xor (1 xor (1 xor 0)) = 1
1 xor (1 xor (0 xor 0)) = 0
1 xor (0 xor (1 xor 1)) = 1
1 xor (0 xor (0 xor 1)) = 0
1 xor (0 xor (1 xor 0)) = 0
1 xor (0 xor (0 xor 0)) = 1
0 xor (1 xor (1 xor 1)) = 1
0 xor (1 xor (0 xor 1)) = 0
0 xor (1 xor (1 xor 0)) = 0
0 xor (1 xor (0 xor 0)) = 1
0 xor (0 xor (1 xor 1)) = 0
0 xor (0 xor (0 xor 1)) = 1
0 xor (0 xor (1 xor 0)) = 1
0 xor (0 xor (0 xor 0)) = 0

etc ...

  • Related