// strings reference

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.

Catégorie
Strings
Returns
integer
In this category
43 of 172

Syntaxe

OCTET_LENGTH(string)
DATALENGTH(string)
LENGTHB(string)

Each block is a separate form. The support table and the examples show which engine takes which.

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Different name or syntax DATALENGTH is the byte counter; no OCTET_LENGTH
PostgreSQL Oui Supported under this name.
MySQL Oui Supported under this name.
SQLite Oui octet_length() from SQLite 3.43
Oracle Different name or syntax LENGTHB is the byte counter

Exemples

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

Bon à savoir

  • '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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// 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.