MySQL CHAR_LENGTH() Function
MySQL CHAR_LENGTH() Function
The CHAR_LENGTH() function counts the total number of characters in a string. Unlike byte-based counters, it treats every Unicode symbol, accented letter, and emoji as one character.
Syntax
CHAR_LENGTH(str)
- str: The input string or column to measure.
- Return value: A non-negative integer count of characters, or
NULLifstrisNULL.
MySQL defines VARCHAR(n) column limits in characters rather than bytes. That makes CHAR_LENGTH() the right tool when validating text against column widths or UI display limits.
Practical Example
Your international store tracks customer names in demo_customers. You want to compare character counts against byte counts before exporting badges.
SELECT
customer_id,
first_name,
CHAR_LENGTH(first_name) AS char_count,
LENGTH(first_name) AS byte_count
FROM demo_customers
ORDER BY customer_id;
| customer_id | first_name | char_count | byte_count |
|---|---|---|---|
| 101 | Alice | 5 | 5 |
| 102 | José | 4 | 5 |
| 103 | Zoë | 3 | 4 |
| 104 | "" | 0 | 0 |
| 105 | NULL | NULL | NULL |
Notice how 'José' has 4 characters but 5 bytes in utf8mb4. The accented 'é' occupies two bytes while counting as a single character.
Common Mistakes & NULL Behavior
- Confusing CHAR_LENGTH() with LENGTH():
LENGTH()counts bytes, not characters. UsingLENGTH()for form validation rejects valid international names containing accents or emoji. - Trailing spaces are counted:
CHAR_LENGTH('Ana ')returns5because spaces are characters. Wrap columns inTRIM()if you want visible character counts only. - NULL propagation: Passing
NULLreturnsNULL, not0. Wrap nullable fields withCOALESCE(first_name, '')when summing text lengths across rows.
Frequently Asked Questions
How does CHAR_LENGTH() count emoji in utf8mb4?
An emoji like '🚀' takes 4 bytes in utf8mb4, yet CHAR_LENGTH('🚀') returns 1.
Does CHAR_LENGTH() work on numeric or date columns?
Yes. MySQL implicitly converts numbers and dates into strings first, so CHAR_LENGTH(1000) returns 4.
Is CHAR_LENGTH() different from CHARACTER_LENGTH()?
No. Both names invoke the exact same function in MySQL, and CHARACTER_LENGTH() exists for ANSI SQL portability.
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.