← Back to SQL, page 21

sql-0409 · Medium mid

What do length('héllo') and length(CAST('héllo' AS BLOB)) return in SQLite?

length('héllo') is 5 because SQLite counts characters for text, while the blob length is 6 because 'é' takes two bytes in UTF-8. Character counts and byte counts differ for any non-ASCII text, which matters for column limits and storage estimates.

Full answer
sql
SELECT length('héllo') AS chars, length(CAST('héllo' AS BLOB)) AS bytes, octet_length('héllo') AS octets;
charsbytesoctets
566

For text values length() returns the number of characters, and for blobs it returns bytes. The UTF-8 encoding of 'é' (U+00E9) is two bytes, so the five-character word occupies six bytes. octet_length(), available in SQLite since 3.43, returns the byte length of text directly, matching the blob figure. PostgreSQL behaves the same way: length() and char_length() count characters and octet_length() counts bytes. A VARCHAR(5) limit in PostgreSQL counts characters, so 'héllo' fits (PostgreSQL behaviour stated, not run here).

sql
SELECT length('héllo') AS chars, length(CAST('héllo' AS BLOB)) AS bytes, octet_length('héllo') AS octets;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • length counts characters for text
  • Blob and octet lengths count bytes
  • UTF-8 uses several bytes for non-ASCII characters

Common mistakes

  • Using character counts to estimate storage

Follow-ups

  • How many bytes does an emoji take in UTF-8?
  • Does SQLite enforce VARCHAR(n) limits?

Tips

  • Separate characters from bytes