MySQL LENGTH() Function
MySQL LENGTH() Function
The LENGTH() function returns the size of a string measured in bytes, not characters. In ASCII text, one character equals one byte, but multibyte utf8mb4 characters take two to four bytes each.
Syntax
LENGTH(str)
- str: The string, column, or binary expression to measure.
- Return value: Integer byte count,
0for'', orNULLwhenstrisNULL.
OCTET_LENGTH() is a synonym for LENGTH(), whereas BIT_LENGTH() returns eight times the byte count. Both byte counters help estimate payload storage, inspect BLOB column sizes, and detect non-ASCII characters inside text columns.
Practical Example
Suppose demo_products contains product names with currency symbols, accents, and emoji. Comparing LENGTH() against CHAR_LENGTH() reveals which rows contain multibyte UTF-8 characters.
SELECT
product_id,
product_name,
LENGTH(product_name) AS bytes_used,
CHAR_LENGTH(product_name) AS char_count
FROM demo_products
ORDER BY product_id;
| product_id | product_name | bytes_used | char_count |
|---|---|---|---|
| 1 | Desk Mat | 8 | 8 |
| 2 | Crème Mug | 10 | 9 |
| 3 | €50 Card | 10 | 8 |
| 4 | Desk 🚀 | 9 | 6 |
In row 2, 'è' uses 2 bytes (10 total bytes vs 9 characters). In row 3, '€' uses 3 bytes, and in row 4 the rocket emoji uses 4 bytes in utf8mb4.
Common Mistakes & NULL Behavior
- Using LENGTH() to enforce UI character limits: Requiring
LENGTH(name)to stay at or below 12 rejects'Crème Brûlée'(12 characters, 14 bytes) because accents inflate the byte count. Always useCHAR_LENGTH()for character counts andVARCHAR(n)limits. - Expecting 0 on NULL:
LENGTH(NULL)returnsNULL, whereasLENGTH('')returns0. Wrap nullable text inCOALESCE(col, '')before summing byte sizes across rows. - SQLite vs. MySQL difference: SQLite's
LENGTH()counts characters on text strings, whereas MySQL'sLENGTH()always counts raw bytes.
Frequently Asked Questions
How can I find rows containing multibyte UTF-8 characters?
Compare LENGTH(col) against CHAR_LENGTH(col) in your WHERE clause. Any row where bytes exceed characters contains at least one multibyte symbol.
Does LENGTH() count trailing spaces?
Yes. Every space occupies 1 byte in UTF-8, so 'hi ' has a LENGTH() of 4.
What does LENGTH() return for a numeric column?
MySQL converts the number to its string representation first, so LENGTH(12345) returns 5.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.