0
0
SQLquery~10 mins

LENGTH and CHAR_LENGTH in SQL - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - LENGTH and CHAR_LENGTH
Input String
Output: Numeric Value
LENGTH counts bytes in a string, CHAR_LENGTH counts characters. They differ when string has multi-byte characters.
Execution Sample
SQL
SELECT LENGTH('café'), CHAR_LENGTH('café');
This query returns the byte length and character length of the string 'café'.
Execution Table
StepFunctionInput StringOutput ValueExplanation
1LENGTH'café'5Counts bytes: 'é' is 2 bytes, total 5 bytes
2CHAR_LENGTH'café'4Counts characters: 'c','a','f','é' = 4 characters
3ENDQuery finishes after both functions return values
💡 Both functions return their counts; LENGTH counts bytes, CHAR_LENGTH counts characters
Variable Tracker
VariableStartAfter LENGTHAfter CHAR_LENGTHFinal
Input String'café''café''café''café'
LENGTH ResultNULL555
CHAR_LENGTH ResultNULLNULL44
Key Moments - 2 Insights
Why does LENGTH('café') return 5 but CHAR_LENGTH('café') returns 4?
Because LENGTH counts bytes and 'é' uses 2 bytes in UTF-8, while CHAR_LENGTH counts characters, so it counts 'é' as one character (see execution_table rows 1 and 2).
Will LENGTH and CHAR_LENGTH always return the same number?
No, they differ when the string contains multi-byte characters like accented letters or emojis, as shown in the example with 'café'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output of LENGTH('café')?
A3
B4
C5
D6
💡 Hint
Check the row where Function is LENGTH and Input String is 'café' in the execution_table.
At which step does CHAR_LENGTH return its value?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look for the row where Function is CHAR_LENGTH in the execution_table.
If the input string was 'cat' (all ASCII), how would LENGTH and CHAR_LENGTH compare?
ALENGTH would be greater than CHAR_LENGTH
BBoth would be equal
CCHAR_LENGTH would be greater than LENGTH
DBoth would be zero
💡 Hint
ASCII characters use 1 byte each, so LENGTH and CHAR_LENGTH count the same number.
Concept Snapshot
LENGTH(string) returns the number of bytes in the string.
CHAR_LENGTH(string) returns the number of characters.
They differ when string has multi-byte characters.
Use LENGTH for byte size, CHAR_LENGTH for character count.
Example: LENGTH('café')=5, CHAR_LENGTH('café')=4.
Full Transcript
This lesson shows how LENGTH and CHAR_LENGTH work in SQL. LENGTH counts bytes in a string, so multi-byte characters like 'é' count as more than one. CHAR_LENGTH counts characters, so 'é' counts as one. For example, 'café' has 5 bytes but 4 characters. The execution table shows LENGTH returns 5 and CHAR_LENGTH returns 4 for 'café'. This difference is important when working with strings containing special characters. ASCII strings have equal LENGTH and CHAR_LENGTH. Remember: LENGTH is byte count, CHAR_LENGTH is character count.