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:
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:
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.
LENGTH()
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.