Lesson

MySQL CHAR_LENGTH() Function

10 min reading
Free Course

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 NULL if str is NULL.

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. Using LENGTH() for form validation rejects valid international names containing accents or emoji.
  • Trailing spaces are counted: CHAR_LENGTH('Ana ') returns 5 because spaces are characters. Wrap columns in TRIM() if you want visible character counts only.
  • NULL propagation: Passing NULL returns NULL, not 0. Wrap nullable fields with COALESCE(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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum