Bit operators
&, |, ^, ~, << and >> on unsigned 64-bit numbers, and the BIT_ functions.
Syntax#
a & b -- bitwise AND
a | b -- bitwise OR
a ^ b -- bitwise XOR
~a -- bitwise NOT
a << n -- shift left
a >> n -- shift rightRemarks#
- Unsigned 64 bits. The operands are read as unsigned 64-bit numbers and the result is an unsigned 64-bit number (
BIGINT UNSIGNED). A negative number is taken as its 64-bit two's complement:-1 & 255is 255 and~0is 18446744073709551615. - Rounding. A fraction is rounded first:
7.6 & 3is8 & 3, which is 0. Text is read as a number:'6' & 3is 2. - Shifts. A shift by 64 or more bits gives 0:
1 << 64is 0,1 << 63is 9223372036854775808,~0 >> 1is 9223372036854775807. NULL. ANULLoperand givesNULL.- Hexadecimal and bit literals.
0x0F & 0x3Cworks on the numbers the literals stand for; a literal of up to 8 bytes is read as its number (see Literals). - Precedence. From the tightest:
^(tighter than*), then<<>>, then&, then|, all looser than+and-and tighter than comparisons:2 + 3 & 4is(2 + 3) & 4,1 | 2 & 3is1 | (2 & 3),2 * 3 ^ 2is2 * (3 ^ 2),6 & 4 = 4compares after the&. BITcolumns andBIT_COUNT. See BIT type andBIT_COUNTon Numeric functions. The aggregatesBIT_AND,BIT_ORandBIT_XORare on Aggregate functions.- The MariaDB dialect has the same operators and rules. Not supported yet:
NO_UNSIGNED_SUBTRACTIONmode (stored, no effect).
Examples#
SELECT 5 & 4, 5 | 2, 5 ^ 1, 1 << 3, 256 >> 2, ~0, ~5, 2 + 3 & 4, 1 | 2 & 3, 2 * 3 ^ 2, NULL & 1, -1 & 255, 7.6 & 3, '6' & 3, 1 << 64, 1 << 63, ~0 >> 1;
SELECT 6 & 4 = 4, 1 | 0 = 1;
```7. Evaluated by the rules above the first gives `4, 7, 4, 8, 64, 18446744073709551615, 18446744073709551610, 4, 3, 2, NULL, 255, 0, 2, 0, 9223372036854775808, 9223372036854775807`.
## See also
* [Operators](/docs/sql-reference/operators)
* [BIT type](/docs/sql-reference/bit-type)
* [Expressions and operator precedence](/docs/sql-reference/expressions)