0
0
MySQLquery~5 mins

LENGTH and CHAR_LENGTH in MySQL

Choose your learning style9 modes available
Introduction

We use LENGTH and CHAR_LENGTH to find out how long a piece of text is. LENGTH counts bytes, CHAR_LENGTH counts characters.

When you want to know how many characters a name or word has.
When you need to check the size of text data before saving it.
When you want to compare text lengths in different languages.
When you want to count characters in a message or comment.
When you want to find out if a text is empty or too long.
Syntax
MySQL
LENGTH(string)
CHAR_LENGTH(string)

LENGTH returns the number of bytes used by the string.

CHAR_LENGTH returns the number of characters in the string.

Examples
Returns 5 because 'hello' has 5 bytes (1 byte per character).
MySQL
SELECT LENGTH('hello');
Returns 5 because 'hello' has 5 characters.
MySQL
SELECT CHAR_LENGTH('hello');
Returns 7 because 'ñ' and 'ú' use 2 bytes each in UTF-8.
MySQL
SELECT LENGTH('ñandú');
Returns 5 because there are 5 characters in the word.
MySQL
SELECT CHAR_LENGTH('ñandú');
Sample Program

This query shows the difference between LENGTH and CHAR_LENGTH for the word 'café'.

MySQL
SELECT LENGTH('café') AS length_bytes, CHAR_LENGTH('café') AS length_chars;
OutputSuccess
Important Notes

For simple English letters, LENGTH and CHAR_LENGTH usually return the same number.

For special characters or accents, LENGTH counts bytes, so it can be higher than CHAR_LENGTH.

Use CHAR_LENGTH when you want to count characters, not bytes.

Summary

LENGTH counts bytes in a string.

CHAR_LENGTH counts characters in a string.

Use these functions to check text size or length in your database.