Sub topic 4
Measuring strings: characters versus bytes
This chapter assumes you know the basic SELECT and WHERE syntax, how PostgreSQL treats NULL, and the difference between text, varchar(n) and char(n). It also assumes your database uses the UTF8 encoding, which is the default on most installations. You can check with SHOW server_encoding;.
Two ways to measure a string
A string has two sizes. Its length in characters is the number of symbols a person would count. Its length in bytes is the space the encoded text takes. In plain ASCII these are equal. In UTF8, a character takes 1 to 4 bytes, so the two numbers can differ.
PostgreSQL has separate functions for each measure:
| Function | Measures | Notes |
|---|---|---|
| `char_length(text)` | Characters | Also spelled `character_length`. |
| `length(text)` | Characters | Same result as `char_length` for text. |
| `octet_length(text)` | Bytes | Depends on the database encoding. |
| `bit_length(text)` | Bits | Always `octet_length * 8`. |
SELECT char_length('héllo') AS chars,
octet_length('héllo') AS bytes,
bit_length('héllo') AS bits;In a UTF8 database this returns 5, 6 and 48. The letter é is one character but takes two bytes (0xC3 0xA9), so the byte count is one higher.
Which function to use
Use char_length when the question is about text as a person sees it. Examples are "is this name longer than 50 letters?" or "how many characters will fit in this display field?".
Use octet_length when the question is about storage or a byte limit. Examples are a payload size cap, a protocol field that holds at most 255 bytes, or a size estimate for a column.
length is accepted by many other databases, so it is a common choice for portable code. Its meaning depends on the argument type, though. For text it counts characters. For bytea (binary data) it counts bytes. This is a common source of confusion when a column type changes.
SELECT length('héllo'::text) AS text_length,
length('héllo'::bytea) AS bytea_length;The first column is 5. The second counts the bytes of the literal as it was entered, which is 6 in a UTF8 session.
Multi-byte characters
Accented letters take two bytes. Most Chinese, Japanese and Korean characters take three. Emoji and rare symbols take four.
SELECT char_length('naïve') AS latin,
octet_length('naïve') AS latin_bytes,
char_length('日本語') AS cjk,
octet_length('日本語') AS cjk_bytes,
char_length(U&'\+01F600') AS emoji,
octet_length(U&'\+01F600') AS emoji_bytes;The results are 5 and 6 for naïve, 3 and 9 for 日本語, and 1 and 4 for the emoji. The U&'...' form is a Unicode escape string. It lets you write a character by its code point, which avoids terminal or editor encoding problems.
A character is not always what you see
char_length counts Unicode code points, not visual symbols. The letter é can be stored as one code point (U+00E9), or as e followed by a combining accent (U+0301). Both display the same.
SELECT char_length(U&'\00E9') AS precomposed,
char_length(U&'e\0301') AS decomposed,
octet_length(U&'e\0301') AS decomposed_bytes,
U&'\00E9' = U&'e\0301' AS equal;This returns 1, 2, 3 and false. The two strings look identical, but PostgreSQL treats them as different values. This causes surprises with length checks, GROUP BY and unique constraints on data from mixed sources, such as text typed on different operating systems.
From PostgreSQL 13, normalize rewrites a string into a standard form. Use NFC to get the precomposed form. This function needs a UTF8 database.
SELECT char_length(normalize(U&'e\0301', NFC)) AS normalized_length,
is_normalized(U&'e\0301', NFC) AS already_nfc;This returns 1 and false.
Length limits on columns
A column declared varchar(n) or char(n) limits the number of characters, not bytes. A multi-byte value can therefore be accepted even when its byte size is above n.
CREATE TABLE tags (name varchar(5));
INSERT INTO tags VALUES ('ééééé'); -- accepted: 5 characters, 10 bytes
INSERT INTO tags VALUES ('éééééé'); -- ERROR: value too long for type character varying(5)The reverse also holds. If a downstream system enforces a byte limit, such as an external API or a fixed-width file, a varchar(n) check does not protect you. Check octet_length as well, with a CHECK constraint:
ALTER TABLE tags
ADD CONSTRAINT tags_name_bytes CHECK (octet_length(name) <= 8);The varchar(n) limit has one quirk. If the extra characters are all spaces, PostgreSQL accepts the value and cuts it to n characters instead of raising an error. This also happens with an explicit cast, such as 'abc '::varchar(3).
Length and char(n)
The char(n) type pads values with spaces up to n characters. The two measuring functions treat this padding differently.
SELECT char_length('ab'::char(5)) AS chars,
octet_length('ab'::char(5)) AS bytes,
char_length('ab'::char(5)::text) AS as_text;char_length ignores trailing spaces for char(n), so it returns 2. octet_length counts the stored padding, so it returns 5. Casting to text removes the padding. Mixing these two functions on char(n) columns can give results that look inconsistent. For this reason, text or varchar is usually the better choice for new columns.
NULL, empty strings and blanks
Measuring functions follow the usual NULL rule: if the input is NULL, the result is NULL. An empty string is a real value with length 0. A string of spaces has a length equal to its number of spaces.
SELECT char_length(NULL) AS null_input,
char_length('') AS empty,
char_length(' ') AS spaces,
char_length(trim(' ')) AS trimmed;The results are NULL, 0, 3 and 0. A filter such as WHERE char_length(note) > 0 removes both NULL and empty values, because the comparison with NULL is not true. To also treat blank text as empty, trim first: WHERE char_length(trim(note)) > 0.
Practical patterns
Find rows that contain multi-byte characters. The two measures are equal only when every character is a single byte:
SELECT id, name
FROM customers
WHERE octet_length(name) <> char_length(name);Count bytes in a way that does not depend on the database encoding, by converting to bytea with an explicit encoding:
SELECT octet_length('héllo') AS database_encoding_bytes,
length(convert_to('héllo', 'UTF8')) AS utf8_bytes;In a UTF8 database both columns are 6. In a database that uses LATIN1, the first would be 5 while the second stays 6. Use convert_to when the byte limit belongs to an external system that requires UTF8.
Cutting a string to a byte budget needs care. left(name, n) counts characters, so it is safe but may still exceed the byte limit. Cutting the bytea form can split a multi-byte character in the middle. A safe approach is to shorten by characters until the byte count fits. For a small, fixed limit this is often enough:
SELECT left(name, 10) AS short_name
FROM customers
WHERE octet_length(left(name, 10)) <= 20;Common mistakes
- Using
octet_lengthto enforce a "maximum 50 characters" rule. Names with accents are rejected too early. - Using
char_lengthto enforce a byte limit from an external system. Multi-byte text can exceed the limit. - Comparing
lengthresults acrosstextandbyteacolumns without noticing that one counts characters and the other bytes. - Expecting visually identical strings to have equal lengths. Normalize with
normalize(..., NFC)first when data comes from mixed sources. - Forgetting that
char_length(NULL)isNULL, which makes aWHEREcondition drop the row.
Exercise
A table has a column title varchar(20). A row holds the value Crème brûlée à la maison entered by a user. Insertion fails with "value too long". Another row holds 20 emoji characters and is accepted. What explains both outcomes, and which query finds rows where the byte size is larger than the character count?
Show answer
varchar(20) limits characters, not bytes. Crème brûlée à la maison has 24 characters, so it is rejected. The 20 emoji are 20 characters, so they are accepted even though they use about 80 bytes. To find rows with multi-byte characters, use SELECT id, title FROM items WHERE octet_length(title) <> char_length(title);.
Exercise
What do char_length(U&'e\0301'), char_length(normalize(U&'e\0301', NFC)) and octet_length('ab'::char(5)) return in a UTF8 database?
Show answer
They return 2, 1 and 5. The decomposed é is two code points. After NFC normalization it is one code point. octet_length counts the padding that char(5) stores.