LENGTH
Description
The LENGTH function returns the byte length of a string (in bytes). This function calculates the number of bytes a string occupies in UTF-8 encoding, not the number of characters.
Note the difference from CHAR_LENGTH:
LENGTH()returns the number of bytesCHAR_LENGTH()andCHARACTER_LENGTH()return the number of characters- For ASCII characters, byte count equals character count
- For multi-byte characters (such as Chinese, emoji), byte count is usually greater than character count
Alias
OCTET_LENGTH()
Syntax
LENGTH(<str>)
Parameters
| Parameter | Description |
|---|---|
<str> | The string whose byte length needs to be calculated. Type: VARCHAR |
Return Value
Returns INT type, representing the byte length of the string.
Special cases:
- If parameter is NULL, returns NULL
- Empty string returns 0
- Result is the number of bytes in UTF-8 encoding
Examples
- ASCII characters (byte count = character count)
SELECT LENGTH('abc'), CHAR_LENGTH('abc');
+---------------+--------------------+
| LENGTH('abc') | CHAR_LENGTH('abc') |
+---------------+--------------------+
| 3 | 3 |
+---------------+--------------------+
- Chinese characters (byte count > character count)
SELECT LENGTH('中国'), CHAR_LENGTH('中国');
+------------------+---------------------+
| LENGTH('中国') | CHAR_LENGTH('中国') |
+------------------+---------------------+
| 6 | 2 |
+------------------+---------------------+
- NULL value handling
SELECT LENGTH(NULL);
+--------------+
| LENGTH(NULL) |
+--------------+
| NULL |
+--------------+