Sub topic 14
Encoding and collation effects on string results
This chapter assumes you know the basic string functions from earlier chapters (char_length, lower, ORDER BY) and can run queries in psql. It covers two database settings that change string results without any change to your SQL: the encoding and the collation.
Two settings, two kinds of effect
An encoding is the rule that maps characters to bytes. A collation is the rule that decides how strings compare and sort, and which characters count as letters or as upper or lower case.
The encoding decides what bytes are stored and how many characters a byte sequence represents. The collation decides ordering and case rules. A mistake with either one gives wrong results without raising an error.
Encoding: server, client and conversion
Each database has one server encoding, set when the database is created. Almost every modern database uses UTF8. Each connection also has a client encoding. PostgreSQL converts text between the two automatically.
SHOW server_encoding;
SHOW client_encoding;
SELECT datname,
pg_encoding_to_char(encoding) AS encoding,
datcollate,
datctype
FROM pg_database;server_encoding is fixed for the life of the database. You can change client_encoding per session with SET client_encoding = 'LATIN1'. If the client encoding cannot represent a character that the server returns, the query fails with an error such as "character with byte sequence ... has no equivalent in encoding". If your application shows garbled text like é instead of é, the client and server disagree about the encoding.
Characters versus bytes
In a UTF8 database, one character can take one to four bytes. char_length counts characters and octet_length counts bytes. Functions such as substring, left, right, strpos and lpad all work in characters, so they never cut a multibyte character in half.
The convert_to function turns text into a bytea value in a chosen encoding. For bytea, length counts bytes.
SELECT length(convert_to('héllo', 'UTF8')) AS utf8_bytes,
length(convert_to('héllo', 'LATIN1')) AS latin1_bytes;This returns 6 and 5. The letter é takes two bytes in UTF8 and one in LATIN1. convert_from(bytes, 'LATIN1') goes the other way, from bytea back to text in the database encoding.
Code points with ascii and chr
SELECT ascii('é') AS code_point,
chr(8364) AS euro_sign;This returns 233 and €. In a UTF8 database, ascii returns the Unicode code point of the first character, despite its name. chr converts a code point to a character. In other multibyte encodings the numbers mean something different, and chr rejects values it cannot represent.
Invalid and zero bytes
PostgreSQL validates text on input. A byte sequence that is not valid in the database encoding is rejected with invalid byte sequence for encoding "UTF8". The zero byte (\0) cannot be stored in any text value. If you need arbitrary binary data, use bytea instead of text.
Normalization: equal-looking strings that differ
Unicode can write é in two ways. One is the single code point U+00E9. The other is e followed by the combining accent U+0301. They look the same on screen but are different strings. This often happens when text comes from different operating systems or keyboards.
SELECT U&'\00E9' = U&'e\0301' AS equal_raw,
normalize(U&'e\0301', NFC) = U&'\00E9' AS equal_normalized,
char_length(U&'e\0301') AS chars;This returns false, true and 2. normalize(text, form) accepts NFC, NFD, NFKC or NFKD, and is_normalized tests a string. Both functions require a UTF8 server encoding. If you compare user-supplied names or emails, normalize them to one form (usually NFC) before storing them.
Collation: how strings compare and sort
A collation has a name, such as "C", "en_US" or an ICU name like "en-US-x-icu". The "C" collation compares raw bytes. Other collations follow language rules: they ignore case at the first level, treat accented letters as close to their base letters, and may ignore punctuation.
Compare the same four values under two collations:
SELECT x
FROM (VALUES ('b'), ('A'), ('a'), ('B')) AS t(x)
ORDER BY x COLLATE "C";This returns A, B, a, b, because uppercase letters have lower byte values than lowercase ones. In a database whose default collation is en_US.UTF-8, the same query without COLLATE "C" returns a, A, b, B. Your default collation decides which of these you see. You can find it in the datcollate column of the pg_database query above.
The collation affects every operation that compares order, not only ORDER BY:
- The operators
<,>,<=,>=andBETWEENon text. minandmaxon text columns.- The sort order of B-tree indexes and the results of
DISTINCTandGROUP BYwhen they are implemented by sorting. The grouping result itself does not change, because equality is still exact. ORDER BYinsidestring_agg, which affects the order of items in the joined text.
Case rules and character classes
The LC_CTYPE setting of the collation decides which characters are letters and how they change case. It affects upper, lower, initcap, ILIKE, case-insensitive regex matching and the regex classes \w and [[:alpha:]].
With a C ctype, only ASCII letters change case. lower('ÀÉ') returns ÀÉ unchanged. With a UTF-8 locale such as en_US.UTF-8, it returns àé. A query that works on your laptop can behave differently on a server created with LC_CTYPE=C.
Choosing a collation per column or expression
You can set a collation on a column, and you can override it for one expression.
CREATE TABLE people (
id int PRIMARY KEY,
name text COLLATE "C"
);
SELECT name
FROM people
ORDER BY name COLLATE "en_US";The collation name must exist in pg_collation. Run SELECT collname FROM pg_collation; to see what your server offers.
PostgreSQL resolves the collation of an expression with these rules:
- An explicit
COLLATEin the expression wins. - Otherwise, the collation of the column is used.
- If two columns with different collations are compared, PostgreSQL raises
could not determine which collation to use for string comparison. Add an explicitCOLLATEto fix it. - Two different explicit
COLLATEclauses in one comparison raisecollation mismatch between explicit collations.
Case-insensitive comparison with nondeterministic collations
A normal collation is deterministic. Two strings are equal only if their bytes are equal, even if the collation sorts them next to each other. With ICU you can define a nondeterministic collation, in which strings that differ only in case count as equal:
CREATE COLLATION case_insensitive (
provider = icu,
locale = 'und-u-ks-level2',
deterministic = false
);
SELECT 'Ana' = 'ana' COLLATE case_insensitive AS same_name;This returns true. It requires a PostgreSQL build with ICU support. Nondeterministic collations are slower, and they cannot be used with LIKE or pattern matching before PostgreSQL 18. For many applications, an expression index on lower(email) (see the indexing chapter) is the simpler choice.
Gotchas
- Operating system upgrades can corrupt indexes. With the libc provider, the sort order comes from the operating system's locale data. After an upgrade that changes the data, an existing B-tree index on a text column may no longer match the order PostgreSQL expects. Lookups can then miss rows. Rebuild such indexes with
REINDEX. Recent PostgreSQL versions record the collation version and warn when it changes. - Pattern matching and indexes. A B-tree index built under a non-
Ccollation cannot serveLIKE 'abc%'. Create it with thetext_pattern_opsoperator class, or build it on a column that usesCOLLATE "C". - Results differ between environments. Test and production databases created with different locales return different sort orders and case results. State the collation explicitly when order matters for a report or a unique rule.
GROUP BYandDISTINCTare not case-folded. With a deterministic collation,'Ana'and'ana'are different groups, whatever the sort order looks like.
Summary table
| Behavior | Controlled by | Example |
|---|---|---|
| Bytes per character | Server encoding | `octet_length('é')` is 2 in UTF8 |
| Text conversion to a client | Client encoding | `SET client_encoding = 'LATIN1'` |
| Sort order | Collation | `ORDER BY x COLLATE "C"` |
| Case change and letter classes | Collation ctype | `lower('ÀÉ')` |
| Equal-looking strings | Unicode normalization | `normalize(x, NFC)` |
Exercise
A table column uses the default en_US.UTF-8 collation. A user reports that SELECT max(code) FROM items returns 'b' when the values are 'B' and 'b'. They expected 'b' to win under byte order. What explains the result, and how would you get a byte-order answer?
Show answer
Under en_US.UTF-8, 'b' sorts before 'B' (lowercase first), so max() returns 'B'. Whichever value the user sees, it follows the language rules of the collation, not byte values. To compare by bytes, use SELECT max(code COLLATE "C") FROM items, which returns 'b' because 'b' (byte 98) is greater than 'B' (byte 66).
Exercise
Two users both enter the name José, but WHERE name = 'José' finds only one of them. char_length shows 4 for one row and 5 for the other. What is happening, and what query shows the fix?
Show answer
One value uses the single code point é (U+00E9) and the other uses e plus the combining accent U+0301, so the strings are different. Normalize both to the same form, for example WHERE normalize(name, NFC) = normalize('José', NFC). Better still, normalize on input with UPDATE people SET name = normalize(name, NFC) so that an ordinary index works.