Lesson

MySQL CHARACTER_LENGTH() Function

10 min reading
Free Course

MySQL CHARACTER_LENGTH() Function

The CHARACTER_LENGTH() function returns the number of characters in a string. It is the ANSI SQL standard synonym for CHAR_LENGTH() and produces identical output in every MySQL version.

Syntax

CHARACTER_LENGTH(str)
  • str: A character string, column, or expression.
  • Return value: Integer count of logical characters, or NULL when str is NULL.

Teams writing portable SQL across MySQL, PostgreSQL, and standard SQL engines often prefer CHARACTER_LENGTH() because other databases recognize the longer name natively.

Practical Example

Suppose the merchandising team in demo_products needs product titles under 20 characters for mobile cards. This query flags titles that exceed the budget and contrasts character length with raw byte storage.

SELECT
    product_id,
    product_name,
    CHARACTER_LENGTH(product_name) AS title_chars,
    LENGTH(product_name) AS title_bytes
FROM demo_products
WHERE CHARACTER_LENGTH(product_name) > 15;
product_id product_name title_chars title_bytes
12 Café Grinder Pro™ 17 19
18 Mechanical Keyboard 19 19
24 USB-C Dock ⚡ 12 15

Notice that 'Café Grinder Pro™' uses 19 bytes in utf8mb4 because 'é' and '™' are multibyte characters. CHARACTER_LENGTH() accurately reports 17 displayed characters.

Common Mistakes & NULL Behavior

  • Mistaking bytes for characters: Unlike LENGTH(), which returns byte size, CHARACTER_LENGTH() always counts characters. On BINARY or BLOB columns, however, each byte is treated as one character.
  • Silent NULL drops in WHERE filters: If product_name is NULL, CHARACTER_LENGTH(product_name) > 15 evaluates to UNKNOWN, so the row disappears from results.
  • Empty strings return zero: An empty string '' returns 0. Combine COALESCE(product_name, '') if empty and missing titles should behave the same way.

Frequently Asked Questions

Should I use CHAR_LENGTH() or CHARACTER_LENGTH() in MySQL?

They behave identically. Choose CHARACTER_LENGTH() for ANSI SQL portability or CHAR_LENGTH() for shorter queries.

Why does CHARACTER_LENGTH() return a smaller number than LENGTH()?

LENGTH() measures raw bytes. Any UTF-8 character beyond basic ASCII uses two to four bytes, making LENGTH() larger than CHARACTER_LENGTH().

Does CHARACTER_LENGTH() ignore spaces?

No. Leading, middle, and trailing spaces all count toward the total character length.

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