MySQL BIT_AND() Function

The MySQL BIT_AND() function is an aggregate function that performs a “bitwise AND” operation on all non-null input values.

The bitwise AND processes two binary numbers of the same length, if both corresponding binary bits are 1, the result value of the bit is 1, otherwise it is 0.

BIT_AND() Syntax

Here is the syntax for MySQL BIT_AND() function:

BIT_AND(expr)

We usually use the BIT_AND() function like this:

SELECT BIT_AND(expr), ...
FROM table_name
[WHERE ...];

Or use the BIT_AND() function with the GROUP BY clause:

SELECT BIT_AND(expr), group_expr1, group_expr2, ...
FROM table_name
[WHERE ...]
GROUP BY group_expr1, group_expr2, ...;

Parameters

expr

Required. A column name or expression. It accepts a numeric or binary value.

Return value

The MySQL BIT_AND() function returns the result of performing a “bitwise AND” operation on all non-null input values, and the result is of the same type as the input parameter.

Note that the BIT_AND() function only handles non-null values. That is, null values ​​are ignored by the BIT_AND() function.

If all input values ​​are nulls, the function will return NULL.

BIT_AND() Examples

To demonstrate usages of the MySQL BIT_AND() function, we simulate a temporary table using the following statement and UNION and SELECT:

SELECT 4 x
UNION
SELECT 5 x
UNION
SELECT 6 x;
+---+
| x |
+---+
| 4 |
| 5 |
| 6 |
+---+
3 rows in set (0.00 sec)

The following statement performs the BIT_AND() operation on the x column:

SELECT BIT_AND(x)
FROM (
    SELECT 4 x
    UNION
    SELECT 5 x
    UNION
    SELECT 6 x
  ) t;
+------------+
| BIT_AND(x) |
+------------+
|          4 |
+------------+

Here, the BIT_AND() function performs a “bitwise AND” operation on the values ​​(4, 5, 6) in the x column, the following shows how is works:

       4 -> 100
       5 -> 101
       6 -> 110
BIT_AND() = 100 = 4

So the BIT_AND() function returns 4.