Available in versions: Dev (3.17) | Latest (3.16) | 3.15 | 3.14 | 3.13 | 3.12 | 3.11 | 3.10 | 3.9 | 3.8 | 3.7

# BIT_COUNT

Applies to ✅ Open Source Edition   ✅ Express Edition   ✅ Professional Edition   ✅ Enterprise Edition

The BIT_COUNT() function counts the number of bits in a value.

SELECT bit_count(5);
create.select(bitCount(5)).fetch();

The result being

+-----------+
| bit_count |
+-----------+
|         2 |
+-----------+

## Dialect support

This example using jOOQ:

bitCount((byte) 5)

Translates to the following dialect specific expressions:

bit_count(5)

-- AURORA_POSTGRES, POSTGRES, REDSHIFT, SQLITE, VERTICA, YUGABYTEDB
CAST(((5 & 1) + ((5 & 2) >> 1) + ((5 & 4) >> 2) + ((5 & 8) >> 3) + ((5 & 16) >> 4) + ((5 & 32) >> 5) + ((5 & 64) >> 6) + ((5 & -128) >> 7)) AS int)

-- BIGQUERY
CAST(((5 & 1) + ((5 & 2) >> 1) + ((5 & 4) >> 2) + ((5 & 8) >> 3) + ((5 & 16) >> 4) + ((5 & 32) >> 5) + ((5 & 64) >> 6) + ((5 & -128) >> 7)) AS int64)

-- COCKROACHDB
CAST(((5 & 1) + ((5 & 2) >> 1) + ((5 & 4) >> 2) + ((5 & 8) >> 3) + ((5 & 16) >> 4) + ((5 & 32) >> 5) + ((5 & 64) >> 6) + ((5 & -128) >> 7)) AS int4)

-- FIREBIRD
CAST((bin_and(5, 1) + bin_shr(
bin_and(5, 2),
1
) + bin_shr(
bin_and(5, 4),
2
) + bin_shr(
bin_and(5, 8),
3
) + bin_shr(
bin_and(5, 16),
4
) + bin_shr(
bin_and(5, 32),
5
) + bin_shr(
bin_and(5, 64),
6
) + bin_shr(
bin_and(5, -128),
7
)) AS integer)

-- H2, HSQLDB
CAST((bitand(5, 1) + (bitand(5, 2) / 2) + (bitand(5, 4) / 4) + (bitand(5, 8) / 8) + (bitand(5, 16) / 16) + (bitand(5, 32) / 32) + (bitand(5, 64) / 64) + (bitand(5, -128) / -128)) AS int)

-- HANA
bitcount(5)

-- INFORMIX
CAST((bitand(5, 1) + (bitand(5, 2) / 2) + (bitand(5, 4) / 4) + (bitand(5, 8) / 8) + (bitand(5, 16) / 16) + (bitand(5, 32) / 32) + (bitand(5, 64) / 64) + (bitand(5, -128) / -128)) AS integer)

-- ORACLE
CAST((bitand(5, 1) + (bitand(5, 2) / 2) + (bitand(5, 4) / 4) + (bitand(5, 8) / 8) + (bitand(5, 16) / 16) + (bitand(5, 32) / 32) + (bitand(5, 64) / 64) + (bitand(5, -128) / -128)) AS number(10))

-- SNOWFLAKE
CAST((bitand(5, 1) + bitshiftright(
bitand(5, 2),
1
) + bitshiftright(
bitand(5, 4),
2
) + bitshiftright(
bitand(5, 8),
3
) + bitshiftright(
bitand(5, 16),
4
) + bitshiftright(
bitand(5, 32),
5
) + bitshiftright(
bitand(5, 64),
6
) + bitshiftright(
bitand(5, -128),
7
)) AS number(10))

-- SQLDATAWAREHOUSE, SYBASE
CAST(((5 & 1) + ((5 & 2) / 2) + ((5 & 4) / 4) + ((5 & 8) / 8) + ((5 & 16) / 16) + ((5 & 32) / 32) + ((5 & 64) / 64) + ((5 & -128) / -128)) AS int)