MySQL CHAR_LENGTH() Function
MySQL CHAR_LENGTH() Function
The CHAR_LENGTH() function returns the number of characters in its argument.
You can also use the CHARACTER_LENGTH() function, as it does the same thing.
Here's an example of using both functions:
SELECT
title,
CHAR_LENGTH(title),
CHARACTER_LENGTH(title)
FROM film;
Result:
In the above example, we select the title field from the film table. We then return the number of characters the value contains, first by using CHAR_LENGTH(title), then by using CHAR_LENGTH(title).
Usage Example
You can use conditional statements to return different results depending on the length of the string. For example, you could do this:
SELECT
title Title_1,
CHAR_LENGTH(title) Length,
IF(CHAR_LENGTH(title) > 15,
CONCAT(LEFT(title,15), '...'), title) Title_2
FROM sakila.film;
Result:
This time we use CHAR_LENGTH() to check the length of the title. If the title is more than a certain number of characters, we add an ellipsis to the title.
CHAR_LENGTH() vs LENGTH()
It's important not to get confused between the CHAR_LENGTH() and LENGTH() functions.
Also, don't forget that CHARACTER_LENGTH() is a synonym of CHAR_LENGTH(). And while we're talking about synonyms, OCTET_LENGTH() is a synonym for LENGTH().
So, just to be clear…
CHAR_LENGTH()
CHARACTER_LENGTH()
Returns the number of characters in its argument.
OCTET_LENGTH()
Returns the length of a string in bytes (not the number of characters).
The examples on this page use the Sakila sample database.