Menu

SQLite length(): Count Characters vs Bytes (Examples)

Updated on

SQLite length(X) counts Unicode code points in a text value, but bytes in a BLOB. It returns NULL for SQL NULL and 0 for an empty string. Use it to measure text or binary values, but do not assume character count and byte count are interchangeable.

Syntax and return values

length(X)
Input Result
Text Number of Unicode code points before the first NUL character
BLOB Number of bytes
SQL NULL SQL NULL
Number Length of its text representation
Empty string '' 0

A Unicode code point is not always the same as a user-perceived character: a combined emoji or a letter plus a combining mark can contain more than one code point.

Count characters versus UTF-8 bytes

In a UTF-8 database, the two Chinese characters below occupy six bytes:

SELECT
    length('你好') AS characters,
    length(CAST('你好' AS BLOB)) AS utf8_bytes;
characters  utf8_bytes
----------  ----------
2           6

Casting text to a BLOB lets length() count encoded bytes rather than characters. The byte count depends on the database text encoding; six bytes is the UTF-8 result, not a universal value for every encoding.

Empty strings, NULL, and numbers

SELECT
    length('') AS empty_string,
    length(NULL) AS missing_value,
    length(12345) AS numeric_text;

Here empty_string is 0, missing_value is SQL NULL, and numeric_text is 5. If you want to display a fallback for a missing value, use ifnull(); do not confuse missing data with an empty string.

Measure values in a table

WITH samples(label, value) AS (
    VALUES
        ('ASCII', 'hello'),
        ('Unicode', '你好'),
        ('missing', NULL)
)
SELECT
    label,
    length(value) AS characters,
    length(CAST(value AS BLOB)) AS encoded_bytes
FROM samples;

On a UTF-8 database, the ASCII row returns 5 and 5; the Unicode row returns 2 and 6; and the missing row returns NULL for both measurements.

Embedded NUL characters

SQLite text can contain char(0), but length() stops counting text at the first NUL:

SELECT
    length('ab' || char(0) || 'cd') AS characters_before_nul,
    length(CAST('ab' || char(0) || 'cd' AS BLOB)) AS stored_bytes;
characters_before_nul  stored_bytes
---------------------  ------------
2                      5

Avoid storing embedded NUL characters in text unless your application explicitly handles them. See the SQLite core function reference and NUL character notes for the precise behavior.

Try it in your browser

Run and edit these statements in the SQLite Playground. The SQL executes in a temporary SQLite database in your browser without a server connection.