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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.