char_length Versus Octet Length Bytes

char_length counts characters while octet_length counts UTF-8 bytes, so multibyte labels diverge before any length limit or threshold is applied.

SqlData Integrity

Code

snippet
WITH labels AS (
    SELECT * FROM (VALUES
        ('order'),
        ('订单'),
        ('café')
    ) AS t(label)
)
SELECT
    label,
    -- char_length counts characters: CJK and accented letters each count 1
    char_length(label) AS chars,
    -- octet_length counts UTF-8 bytes: CJK chars take 3 bytes, é takes 2
    octet_length(label) AS bytes,
    -- bytes and characters can diverge widely; pick the unit before any length check
    octet_length(label) - char_length(label) AS gap
FROM labels
ORDER BY gap DESC;

What the demo counts

Three labels, order, the Chinese word for order and café, run through both measures. char_length prints 5, 2, 4, counting code points; octet_length prints 5, 6, 5, counting UTF-8 bytes where each CJK character takes three and the accented e takes two.

The gap column subtracts the two: 0 for the ASCII label, 4 for the Chinese pair, 1 for the accented word. Ordered descending, the output ranks the divergence, which is the number a byte-based length limit cares about before any validation runs.

Caveats and details

  • varchar(n) limits characters; storage and wire size follow bytes.
  • The same text changes size across encodings; UTF-8 is assumed here.

Interactive Tools for This Topic

FAQ

Which length should a validation limit use?
Whichever the consumer enforces: char_length for SQL varchar limits, octet_length for byte-sized transports. The demo prints both plus the gap for each label.