// math reference

SQL bitwise operators

Bit flags packed into one integer are tested with bitwise operators. The symbols are mostly shared, with two traps: ^ and Oracle.

Категория
Math
Returns
integer
In this category
81 of 82

Синтаксис

a & b
a | b
a ^ b
~a
a << n
a >> n

Each block is a separate form. The support table and the examples show which engine takes which.

Поддержка движка

ДвижокSupportЗаметки
SQL Server Да & | ^ ~; << >>, LEFT_SHIFT, RIGHT_SHIFT, BIT_COUNT, GET_BIT and SET_BIT from 2022
PostgreSQL Да # is XOR (^ is power); bit_count() for bit strings and bytea
MySQL Да all six plus BIT_COUNT(); results are unsigned 64-bit
SQLite Да & | ~ << >>; no XOR operator
Oracle Different name or syntax BITAND() is the documented scalar; BIT_AND_AGG, BIT_OR_AGG and BIT_XOR_AGG aggregates from 21c

Примеры

MySQL

SELECT 5 & 3 AS b_and, 5 | 3 AS b_or, 5 ^ 3 AS b_xor, 1 << 4 AS shl, BIT_COUNT(255) AS ones;  -- 1, 7, 6, 16, 8

PostgreSQL

SELECT 5 & 3 AS b_and, 5 | 3 AS b_or, 5 # 3 AS b_xor, 5 ^ 3 AS power, ~5 AS b_not;  -- 1, 7, 6, 125, -6

SQL Server

SELECT 5 & 3 AS b_and, 5 ^ 3 AS b_xor, 1 << 4 AS shl, BIT_COUNT(255) AS ones, GET_BIT(5, 0) AS bit0;  -- 1, 6, 16, 8, 1

Oracle

SELECT BITAND(5, 3) AS b_and, 5 + 3 - 2 * BITAND(5, 3) AS b_xor FROM dual;  -- 1, 6

Полезно знать

  • ^ is XOR on SQL Server and MySQL but exponentiation on PostgreSQL: 5 ^ 3 is 6 on MySQL and 125 on PostgreSQL. PostgreSQL's XOR is #; SQLite has none, so write (a | b) - (a & b).
  • MySQL returns unsigned 64-bit results: ~5 is 18446744073709551610, not -6.
  • On SQL Server, << and >> and the BIT_COUNT, GET_BIT and SET_BIT functions arrived in SQL Server 2022.
  • A filter such as WHERE flags & 4 <> 0 cannot seek an index on flags. Separate boolean columns or a computed column can be indexed.

Questions about & | ^ ~ << >>

How do I check whether a flag bit is set?

AND with the flag and compare with zero: WHERE flags & 4 <> 0. In Oracle: WHERE BITAND(flags, 4) <> 0.

What is the XOR operator in PostgreSQL?

#. The ^ operator raises to a power, so 2 ^ 3 is 8.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.