SQL reference (MySQL and MariaDB dialects)

Bit operators

&, |, ^, ~, << and >> on unsigned 64-bit numbers, and the BIT_ functions.

Syntax#

SQL
a & b          -- bitwise AND
a | b          -- bitwise OR
a ^ b          -- bitwise XOR
~a             -- bitwise NOT
a << n         -- shift left
a >> n         -- shift right

Remarks#

  • 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 & 255 is 255 and ~0 is 18446744073709551615.
  • Rounding. A fraction is rounded first: 7.6 & 3 is 8 & 3, which is 0. Text is read as a number: '6' & 3 is 2.
  • Shifts. A shift by 64 or more bits gives 0: 1 << 64 is 0, 1 << 63 is 9223372036854775808, ~0 >> 1 is 9223372036854775807.
  • NULL. A NULL operand gives NULL.
  • Hexadecimal and bit literals. 0x0F & 0x3C works 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 & 4 is (2 + 3) & 4, 1 | 2 & 3 is 1 | (2 & 3), 2 * 3 ^ 2 is 2 * (3 ^ 2), 6 & 4 = 4 compares after the &.
  • BIT columns and BIT_COUNT. See BIT type and BIT_COUNT on Numeric functions. The aggregates BIT_AND, BIT_OR and BIT_XOR are on Aggregate functions.
  • The MariaDB dialect has the same operators and rules. Not supported yet: NO_UNSIGNED_SUBTRACTION mode (stored, no effect).

Examples#

SQL
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)