← Back to SQL, page 8

sql-0145 · Medium mid

What do LENGTH('café') and the byte length of the same string return?

LENGTH counts characters, so it returns 4. The UTF-8 encoding uses 5 bytes, because 'é' takes two. In SQLite, LENGTH(CAST(x AS BLOB)) or OCTET_LENGTH gives the byte count; PostgreSQL has OCTET_LENGTH. Column limits such as VARCHAR(n) count characters in PostgreSQL.

Full answer
sql
SELECT LENGTH('café') AS chars, LENGTH(CAST('café' AS BLOB)) AS bytes;
charsbytes
45
sql
SELECT LENGTH('café') AS chars, OCTET_LENGTH('café') AS bytes;
charsbytes
45

Both engines count 4 characters and 5 bytes. The difference matters when an external system limits bytes (some protocols, older MySQL utf8 indexes) while the database limits characters.

Characters can also be composed differently. 'é' can be one code point, or 'e' followed by a combining accent, which LENGTH counts as two. Normalizing text to one form (NFC) before storage avoids strings that look equal but compare unequal; neither engine does this automatically.

sql
SELECT LENGTH('café') AS chars, LENGTH(CAST('café' AS BLOB)) AS bytes;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • LENGTH counts characters
  • UTF-8 bytes can exceed the character count
  • OCTET_LENGTH or a BLOB cast gives bytes
  • Combining characters change character counts

Common mistakes

  • Assuming one character is one byte
  • Comparing visually equal strings in different Unicode forms

Follow-ups

  • How does VARCHAR(10) count in PostgreSQL?
  • How would you find rows with non-ASCII characters?

Tips

  • Mention Unicode normalization briefly