0
0
SQLquery~5 mins

LENGTH and CHAR_LENGTH in SQL

Choose your learning style9 modes available
Introduction
These functions help you find out how many characters or bytes are in a text. This is useful when you want to check the size of words or sentences stored in your database.
When you want to count how many characters are in a username to enforce length rules.
When you need to find the size of a text message before sending it.
When checking if a product description is too long for display.
When comparing the length of two different text fields.
When validating input length in a database query.
Syntax
SQL
LENGTH(string)
CHAR_LENGTH(string)
LENGTH counts the number of bytes used by the string, which can be different from the number of characters if the string contains multi-byte characters.
CHAR_LENGTH counts the number of characters, regardless of how many bytes each character uses.
Examples
Returns 5 because 'hello' has 5 characters and each is one byte.
SQL
SELECT LENGTH('hello');
Also returns 5 because there are 5 characters.
SQL
SELECT CHAR_LENGTH('hello');
Returns 5 because the 'é' character uses 2 bytes in UTF-8 encoding.
SQL
SELECT LENGTH('café');
Returns 4 because there are 4 characters.
SQL
SELECT CHAR_LENGTH('café');
Sample Program
This query shows the difference between LENGTH and CHAR_LENGTH for the word 'database'.
SQL
SELECT LENGTH('database') AS length_bytes, CHAR_LENGTH('database') AS length_chars;
OutputSuccess
Important Notes
If your text contains only simple ASCII characters, LENGTH and CHAR_LENGTH will return the same number.
For languages with special characters (like accented letters or emojis), LENGTH may return a larger number than CHAR_LENGTH.
Use CHAR_LENGTH when you want to count characters as people see them, not bytes.
Summary
LENGTH counts bytes, CHAR_LENGTH counts characters.
They help check text size in databases.
Use CHAR_LENGTH for user-friendly character counts.