// math reference

SQL BITAND function

Returns the bitwise AND of two integers: BITAND(12, 10) is 8: each output bit is set only where both inputs have it.

カテゴリ
Math
Returns
integer
In this category
55 of 82

構文

BITAND(a, b)  -- Oracle
a & b  -- the other engines

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

エンジンサポート

エンジンSupportメモ
SQL Server はい & operator; BITAND does not exist as a name
PostgreSQL はい & operator on integer types
MySQL はい & operator; also | ^ ~ << >> (^ is bitwise XOR)
SQLite はい & operator on integers
Oracle はい BITAND(a, b) function; there is no & operator in Oracle SQL

例

PostgreSQL

SELECT 12 & 10 AS and_result;  -- 8, also on SQL Server, MySQL and SQLite

Oracle

SELECT BITAND(12, 10) AS and_result FROM dual;  -- 8

PostgreSQL

SELECT COUNT(*) FROM users WHERE (permissions & 4) <> 0;  -- has the write flag

知っておくと便利なこと

  • Same operation, different syntax: Oracle wraps it in a function, everyone else uses the infix & operator.
  • Fractional operands are handled inconsistently: SQL Server and PostgreSQL reject them with a type error, while MySQL rounds (12.5 & 3 is 13 & 3 = 1) and SQLite and Oracle BITAND truncate (12 & 3 = 0).
  • Flags decode with masks: (flags & 4) <> 0 tests the third bit; BITAND(flags, 4) on Oracle does the same.

Questions about BITAND

Is BITAND available outside Oracle?

The name is Oracle-only, but the operation is universal: write a & b on SQL Server, PostgreSQL, MySQL and SQLite for the identical result.

How do I test whether a bit flag is set?

Mask and compare: (flags & 4) <> 0 checks the bit worth 4. Oracle: BITAND(flags, 4) > 0.

Can I use & on decimal columns?

Not reliably. SQL Server and PostgreSQL reject decimal operands; MySQL and SQLite silently convert them to integers, which can hide a wrong column. Cast to an integer type first, or store flags as integers.

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.