// strings reference

SQL BIT_LENGTH function

Counts bits rather than bytes or characters. Rarely needed, and it inherits every encoding surprise of byte length.

類別
Strings
Returns
integer
In this category
44 of 172

語法

BIT_LENGTH(string)

引擎支援

引擎Support備註
SQL Server Not built in No built-in equivalent.
PostgreSQL 是 Supported under this name.
MySQL 是 Supported under this name.
SQLite Not built in No built-in equivalent.
Oracle Not built in No built-in equivalent.

範例

PostgreSQL

SELECT BIT_LENGTH('héllo') AS bits, OCTET_LENGTH('héllo') AS bytes;
-- 48, 6

MySQL

SELECT BIT_LENGTH('é') AS bits, CHAR_LENGTH('é') AS chars;
-- 16, 1

小知識

  • It is literally OCTET_LENGTH * 8: 'héllo' is 48 bits in UTF-8, 5 characters. All the same encoding caveats apply.
  • PostgreSQL and MySQL have it; SQL Server, SQLite and Oracle do not. Multiply DATALENGTH or LENGTHB by 8 instead.
  • MySQL's BIT_LENGTH always reflects the string's charset encoding: utf8mb4 data counts real UTF-8 bytes.
  • For a blob or binary column it counts the raw bytes' bits, which is the one case where it is unambiguous.

Questions about BIT_LENGTH

When would I use bits instead of bytes?

Mostly when a protocol or document spec states limits in bits. Bytes are the practical unit everywhere else.

Is BIT_LENGTH affected by charset?

Yes. It measures the encoded bytes' bits, so the same string has different BIT_LENGTH under latin1 and utf8mb4 in MySQL.

What is the Oracle equivalent?

LENGTHB * 8. Oracle has no BIT_LENGTH; its byte counter is LENGTHB.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, MySQL.

// fewer lookups

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.