SQL BIT_AND function
ANDs the values of a group together bit by bit.
- Category
- Aggregates
- Returns
integer- In this category
- 41 of 52
Syntax
BIT_AND(x) | BIT_AND_AGG(x)
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Not built in | No built-in equivalent. |
| PostgreSQL | Yes | aggregate over integer and bit types; empty group returns NULL |
| MySQL | Yes | 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 |
Examples
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;
Good to know
- 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.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, MySQL, Oracle.
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.