Bit functions and operators
Bitwise operators
Section titled “Bitwise operators”Bitwise operators work on the bits of integer values. The operands must be integers (BIT values are not allowed); other numeric types are converted to BIGINT, and the result is a BIGINT.
| Operator | Operation | Example | Result |
|---|---|---|---|
& |
Bitwise AND | 17 & 3 |
1 |
| |
Bitwise OR | 17 | 3 |
19 |
^ |
Bitwise XOR | 17 ^ 3 |
18 |
~ |
Bitwise NOT (unary): inverts every bit | ~17 |
-18 |
<< |
Shift left by the number of bits on the right | 17 << 3 |
136 |
>> |
Shift right by the number of bits on the right | 17 >> 3 |
2 |
BIT_AND, BIT_OR, BIT_XOR
Section titled “BIT_AND, BIT_OR, BIT_XOR”BIT_AND(expr)BIT_OR(expr)BIT_XOR(expr)Aggregate functions that combine the values of an integer expression over all rows with bitwise AND, OR or XOR. If no row qualifies, the result is NULL. Return type: BIGINT.
The products with ids 1, 3 and 5 give the same results as the operators applied to those numbers:
SELECT 1&3&5, BIT_AND(id), 1|3|5, BIT_OR(id), 1^3^5, BIT_XOR(id)FROM productWHERE id IN (1, 3, 5);| 1&3&5 | bit_and(id) | 1|3|5 | bit_or(id) | 1^3^5 | bit_xor(id) |
|---|---|---|---|---|---|
| 1 | 1 | 7 | 7 | 7 | 7 |
A typical use is combining flags stored as bits: BIT_OR(flags) tells which flags are set in at least one row, BIT_AND(flags) which are set in every row.
BIT_COUNT
Section titled “BIT_COUNT”BIT_COUNT(expr)Returns the number of bits set to 1 in an integer. It is not an aggregate function. Return type: INT.
SELECT id, BIT_COUNT(id) FROM product WHERE id IN (1, 3, 5, 255) ORDER BY id;| id | bit_count(id) |
|---|---|
| 1 | 1 |
| 3 | 2 |
| 5 | 2 |
| 255 | 8 |