LENGTH() returns bytes. Use CHAR_LENGTH() when you need the number of characters.
LENGTH() to return the number of bytes in a string.
SELECT LENGTH('Welcome');
The output is 7
SELECT LENGTH('hellow') AS L1, LENGTH(' hellow ') AS L2;
output
| L1 | L2 |
|---|---|
| 6 | 10 |
SELECT id, name, LENGTH(name) FROM `student`
We will get a list of id , name and length like this
1 John Deo 8
2 Max Ruin 8
3 Arnold 6
We can also use length in numeric field like this
SELECT id, name, LENGTH(name),LENGTH(mark) FROM `student`
Output will be 2 for marks less than 100 and more than 9 ( two digits)
SELECT id, name FROM `student` WHERE LENGTH(mark) <=1
This can include single-digit values as well as empty-looking values, because numeric data is converted to text for LENGTH(). LENGTH() returns the number of bytes, while CHAR_LENGTH() returns the number of characters. With UTF-8, one character can occupy multiple bytes.
SELECT LENGTH(_utf8mb4'海豚') AS bytes, CHAR_LENGTH(_utf8mb4'海豚') AS characters;
The result is:
6, 2
That is 6 bytes and 2 characters.
Number of characters present in a stringAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.