Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use aggregate function bit_xor in postgres

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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 …

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading