Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - length() vs char_length()

Tags:

string

mysql

People also ask

What is the difference between CHAR_LENGTH and Character_length?

CHAR_LENGTH vs CHARACTER_LENGTH (any difference)CHAR_LENGTH Returns the length of a string (in characters) CHARACTER_LENGTH Returns the length of a string (in characters) I was looking through the SQL string function on w3sch and I saw this, the description is the same.

What is length function in MySQL?

The LENGTH() function returns the length of a string (in bytes).

How do I count the number of characters in a string in MySQL?

CHAR_LENGTH() function MySQL CHAR_LENGTH() returns the length (how many characters are there) of a given string. The function simply counts the number characters and ignore whether the character(s) are single-byte or multi-byte.


LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC in UTF-8) even though it's only one character.


varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.