SQL BIT_LENGTH function
Counts bits rather than bytes or characters. Rarely needed, and it inherits every encoding surprise of byte length.
- Kategorie
- Strings
- Returns
integer- In this category
- 44 of 172
Syntax
BIT_LENGTH(string)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Not built in | No built-in equivalent. |
| PostgreSQL | Ja | Supported under this name. |
| MySQL | Ja | Supported under this name. |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Not built in | No built-in equivalent. |
Beispiele
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
Gut zu wissen
- 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.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, MySQL.
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.