---
title: "Bit functions and operators"
description: "CoraDB bitwise operators &, |, ^, ~, << and >>, the aggregate functions BIT_AND, BIT_OR and BIT_XOR, and BIT_COUNT, with verified examples."
url: "https://www.coradb.ai/manual/sql/function/bit_fn.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/function/bit_fn.md"
product: "CoraDB"
version: "1.0"
keywords: "bitwise operators, bit_and, bit_or, bit_xor, bit_count, bit shift, bitwise and, bitwise or, xor, coradb"
---

# Bit functions and operators

## Bitwise operators

Bitwise operators work on the bits of integer values. The operands must be integers (`BIT` values are not allowed); other numeric types are converted to `BIGINT`, and the result is a `BIGINT`.

| Operator | Operation | Example | Result |
|---|---|---|---:|
| `&` | Bitwise AND | `17 & 3` | 1 |
| `\|` | Bitwise OR | `17 \| 3` | 19 |
| `^` | Bitwise XOR | `17 ^ 3` | 18 |
| `~` | Bitwise NOT (unary): inverts every bit | `~17` | -18 |
| `<<` | Shift left by the number of bits on the right | `17 << 3` | 136 |
| `>>` | Shift right by the number of bits on the right | `17 >> 3` | 2 |

## BIT_AND, BIT_OR, BIT_XOR

```text
BIT_AND(expr)
BIT_OR(expr)
BIT_XOR(expr)
```

Aggregate functions that combine the values of an integer expression over all rows with bitwise AND, OR or XOR. If no row qualifies, the result is `NULL`. **Return type:** BIGINT.

The products with ids 1, 3 and 5 give the same results as the operators applied to those numbers:

```sql
SELECT 1&3&5, BIT_AND(id), 1|3|5, BIT_OR(id), 1^3^5, BIT_XOR(id)
FROM product
WHERE id IN (1, 3, 5);
```

| 1&3&5 | bit_and(id) | 1\|3\|5 | bit_or(id) | 1^3^5 | bit_xor(id) |
|---:|---:|---:|---:|---:|---:|
| 1 | 1 | 7 | 7 | 7 | 7 |

A typical use is combining flags stored as bits: `BIT_OR(flags)` tells which flags are set in at least one row, `BIT_AND(flags)` which are set in every row.

## BIT_COUNT

```text
BIT_COUNT(expr)
```

Returns the number of bits set to 1 in an integer. It is not an aggregate function. **Return type:** INT.

```sql
SELECT id, BIT_COUNT(id) FROM product WHERE id IN (1, 3, 5, 255) ORDER BY id;
```

| id | bit_count(id) |
|---:|---:|
| 1 | 1 |
| 3 | 2 |
| 5 | 2 |
| 255 | 8 |
