SQL OCTET_LENGTH function
Counts bytes, not characters. The number that matters for storage limits, index key lengths and wire size, and it diverges from CHAR_LENGTH on any accent.
- Категория
- Strings
- Returns
integer- In this category
- 43 of 172
Синтаксис
OCTET_LENGTH(string)
DATALENGTH(string)
LENGTHB(string)
Each block is a separate form. The support table and the examples show which engine takes which.
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Different name or syntax | DATALENGTH is the byte counter; no OCTET_LENGTH |
| PostgreSQL | Да | Supported under this name. |
| MySQL | Да | Supported under this name. |
| SQLite | Да | octet_length() from SQLite 3.43 |
| Oracle | Different name or syntax | LENGTHB is the byte counter |
Примеры
PostgreSQL
SELECT OCTET_LENGTH('héllo') AS bytes, CHAR_LENGTH('héllo') AS chars;
-- 6, 5
Oracle
SELECT LENGTHB('é') AS bytes FROM dual; -- 2
SQL Server
SELECT LEN(N'ab') AS chars, DATALENGTH(N'ab') AS bytes; -- 2, 4
Полезно знать
- 'héllo' is 5 characters and 6 bytes in UTF-8; an emoji is 1 character and 4 bytes. CHAR_LENGTH for display, OCTET_LENGTH for byte limits.
- SQL Server's LEN ignores trailing spaces while DATALENGTH does not, and for nvarchar DATALENGTH counts 2 bytes per character (UTF-16).
- Oracle's LENGTHB reflects the database charset: AL32UTF8 gives true UTF-8 byte counts; older single-byte charsets count 1 per character they can store.
- MySQL's OCTET_LENGTH is an exact synonym of LENGTH, which is why MySQL's LENGTH surprises people who expect characters.
Questions about OCTET_LENGTH
When do I need bytes instead of characters?
Storage limits, index key lengths, VARCHAR(n) in byte semantics, and wire payloads all count bytes. Display widths and truncation count characters.
What is the SQL Server version of OCTET_LENGTH?
DATALENGTH, but it measures the stored bytes of the value, so nvarchar data counts 2 bytes per character and trailing spaces are included.
Is OCTET_LENGTH ever the same as LENGTH?
Yes, for pure ASCII in a single-byte encoding: 1 byte per character. Accents, CJK and emoji break the equality.
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: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.