title | description | author | ms.author | ms.reviewer | ms.date | ms.service | ms.subservice | ms.topic | f1_keywords | helpviewer_keywords | dev_langs | monikerRange | ||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
BIT_COUNT (Transact-SQL) |
Transact-SQL reference for the BIT_COUNT function. |
thesqlsith |
derekw |
randolphwest |
07/26/2022 |
sql |
t-sql |
reference |
|
|
|
>= sql-server-ver16 || >= sql-server-linux-ver16 || = azuresqldb-mi-current ||= azuresqldb-current || =fabric |
[!INCLUDE SQL Server 2022, SQL Database, SQL Managed Instance FabricSE FabricDW]
BIT_COUNT takes one parameter and returns the number of bits set to 1 in that parameter as a bigint type.
:::image type="icon" source="../../includes/media/topic-link-icon.svg" border="false"::: Transact-SQL syntax conventions
BIT_COUNT ( expression_value )
Any integer or binary expression that isn't a large object (LOB).
bigint
BIT_COUNT doesn't cast prior to counting the number of bits. This is because the same number can have a different number of ones in its binary representation depending on the data type.
For example, SELECT BIT_COUNT (CAST (-1 as smallint))
and SELECT BIT_COUNT (CAST (-1 as int))
will return 16 and 32 respectively. This is intended, as the binary representation of -1
can have a different number of bits set to 1 depending on the data type.
In the initial implementation, Distributed Query functionality for the bit manipulation functions within linked server or ad hoc queries (OPENQUERY) won't be supported.
In the following example, the number of bits set to 1
in a binary value are calculated.
SELECT BIT_COUNT ( 0xabcdef ) as Count;
The result is 17
. This is because 0xabcdef
in binary is 1010 1011 1100 1101 1110 1111
, and there are 17 bits with a value set to 1
.
In the following example, the number of bits set to 1
in an integer are calculated.
SELECT BIT_COUNT ( 17 ) as Count;
The result is 2
. This is because 17
in binary is 0001 0001
, and there are only 2 bits with a value set to 1
.