// aggregates reference

SQL BIT_AND function

ANDs the values of a group together bit by bit.

類別
Aggregates
Returns
integer
In this category
41 of 52

語法

BIT_AND(x) | BIT_AND_AGG(x)

引擎支援

引擎Support備註
SQL Server Not built in No built-in equivalent.
PostgreSQL 是 aggregate over integer and bit types; empty group returns NULL
MySQL 是 empty or all-NULL group returns all-ones 18446744073709551615, not 0
SQLite Not built in No built-in equivalent.
Oracle Different name or syntax 21c+: BIT_AND_AGG; empty or all-NULL group returns 0

範例

MySQL

SELECT user_id, BIT_AND(perm_bits) FROM grants GROUP BY user_id;

PostgreSQL

SELECT bit_and(x) FROM (VALUES (6), (3)) v(x); -- 2

Oracle

SELECT user_id, BIT_AND_AGG(perm_bits) FROM grants GROUP BY user_id;

小知識

  • The AND identity is all ones, so MySQL's empty-group answer is 18446744073709551615, surprising next to BIT_OR's 0. PostgreSQL returns NULL for an empty group, and Oracle's BIT_AND_AGG returns 0.
  • NULLs are skipped, like every standard aggregate.
  • Check 'all rows grant this permission' with BIT_AND(perm) = perm: any 0 bit anywhere clears it.

Questions about BIT_AND

Why does an empty group return all ones?

All-ones is the AND identity: AND-ing nothing together must not change anything.

How do I check all flags are set?

BIT_AND(mask) = mask: if any row lacks a bit, the aggregate loses it.

What about PostgreSQL?

bit_and(x) is a built-in aggregate over smallint, integer, bigint and bit columns: SELECT bit_and(perm_bits) FROM grants works as-is.

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: PostgreSQL, MySQL, 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.