// strings reference

SQL LENGTH function

Returns how long a string is. The catch is the unit: LEN and LENGTH usually count characters, but MySQL's LENGTH counts bytes, which differs as soon as accents or emoji appear.

Категория
Strings
Returns
integer
In this category
3 of 172

Синтаксис

LEN(string)  -- SQL Server
LENGTH(string)
CHAR_LENGTH(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 spelled LEN; ignores trailing spaces; DATALENGTH counts bytes
PostgreSQL Да Supported under this name.
MySQL Different name or syntax LENGTH counts bytes, CHAR_LENGTH counts characters
SQLite Да Supported under this name.
Oracle Да Supported under this name.

Примеры

PostgreSQL

-- LENGTH counts characters on PostgreSQL, SQLite and Oracle
SELECT LENGTH('héllo') AS chars;  -- 5

MySQL

SELECT LENGTH('héllo') AS bytes, CHAR_LENGTH('héllo') AS chars;
-- 6, 5

Полезно знать

  • MySQL: LENGTH('é') is 2 (UTF-8 bytes), CHAR_LENGTH('é') is 1. Use CHAR_LENGTH for user-visible text.
  • SQL Server's LEN ignores trailing spaces: LEN('ab ') is 2. DATALENGTH keeps them but counts bytes, so DATALENGTH(N'ab ') is 6.
  • PostgreSQL has LENGTH and CHAR_LENGTH (characters) and OCTET_LENGTH (bytes). Oracle's LENGTH counts characters and LENGTHB counts bytes. SQLite's LENGTH counts characters for text and bytes for blobs.

Questions about LENGTH / LEN

Does LENGTH count characters or bytes?

On MySQL, bytes, so 'é' counts as 2 and an emoji as 4. CHAR_LENGTH counts characters. PostgreSQL's LENGTH counts characters and OCTET_LENGTH counts bytes.

Why does LEN ignore my trailing spaces?

SQL Server's LEN excludes trailing spaces by design. DATALENGTH does not, but counts bytes, not characters.

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

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