Shelves / Internationalisation
IN·02
Comparing, Sorting and Searching Text
Why "alphabetical order" depends on the language: the Unicode Collation Algorithm and its levels, CLDR tailorings for Swedish, German, Turkish and Indic scripts, numeric ordering, case mapping versus case folding, case- and accent-insensitive comparison, collations in PostgreSQL and the index corruption a collation upgrade can cause, and multilingual search with tokenisers, folding and transliteration; with a lab that sorts the same names under six PostgreSQL collations.
Start here: one list, five orders
TiffinBox sorts dish and kitchen names. The lab put the same eighteen names into PostgreSQL 16 and sorted them under different collations:
| Collation | First names | Last names | What's notable |
|---|---|---|---|
C (byte order) |
10 idlis, 2 dosas, Apple, Istanbul… | …Österreich, éclair, İzmir, ılık | every capital before every lowercase; every accented letter after z |
und-x-icu (Unicode default) |
10 idlis, 2 dosas, Äpfel, apple, Apple, eclair, éclair… | …Zebra cake, zeera rice, Zucker | case and accents interleaved, as people expect |
de-x-icu (German) |
same as default | ||
sv-x-icu (Swedish) |
…apple, Apple… | …Zucker, Äpfel, Österreich | in Swedish, Ä and Ö are separate letters after Z |
tr-x-icu (Turkish) |
…Écrin, ılık, Istanbul, İzmir… | dotless ı is its own letter, before dotted i |
And two more lessons:
- Numbers in text: by default
Order 10, Order 100, Order 2, Order 9; with numeric collation (und-u-kn-true)Order 2, Order 9, Order 10, Order 100. - Case- and accent-insensitive equality: with a nondeterministic collation at strength level 1,
eclair = Éclair,CRÈME = cremeandstraße = STRASSEwere all true. Comparing withlower()gave false for all three.
There's no single "correct" order of strings: it depends on the reader's language. This chapter explains how collation works, how to choose one, and how to search text people type in many scripts.
How deep to go
Volume 17 defines six mastery levels. For comparing, sorting and searching:
| Level | What you can do |
|---|---|
| L1 | Use the platform's locale-aware comparison instead of < on strings |
| L2 | Sort lists correctly per user locale; do case-insensitive matching properly |
| L3 | Explain collation levels, tailorings, folding and normalisation, and choose database collations |
| L4 | Diagnose wrong orders, missing matches, slow queries and collation-version index corruption |
| L5 | Design multilingual search: analysers per language, transliteration, ranking |
| L6 | Tune collation and search for scripts and languages with little library support |
Why byte order is wrong
Comparing strings with < compares code points (or bytes, or UTF-16 units). That order is an accident of history: uppercase before lowercase, accented letters after z, and digits compared one character at a time. It's fine for machine keys (IDs, hashes, file names in a build) and wrong for anything a person reads.
The Unicode Collation Algorithm
The Unicode Collation Algorithm (UCA, UTS #10) gives every character a sequence of weights at several levels, and compares strings level by level:
| Level | Compares | Example difference |
|---|---|---|
| 1, primary | base letters | a vs b |
| 2, secondary | accents and diacritics | e vs é |
| 3, tertiary | case and variants | e vs E |
| 4, quaternary | punctuation, when set to matter | "co-op" vs "coop" |
| identical | code points, as a tie-breaker | NFC vs NFD forms |
Two strings are compared on primary weights for the whole string first; only if those tie are accents compared, then case. That's why apple, Apple, Äpfel sit together (same primary letters until p/f) and eclair < éclair < Écrin (the primary difference at the third letter, l vs r, outranks every accent difference).
The default table (DUCET, and CLDR's root collation) gives a reasonable order for all scripts at once. Tailorings adjust it per language:
| Language | Tailoring |
|---|---|
| Swedish, Finnish | å, ä, ö are separate letters after z |
| German (dictionary) | ä = a, ö = o, ü = u at the primary level; the "phonebook" variant sorts ä as ae |
| Spanish | ñ is a letter after n |
| Turkish | ı (dotless) and i (dotted) are different letters, with their own capitals I and İ |
| Danish, Norwegian | æ, ø, å after z, in that order |
| Lithuanian | y sorts as i |
| Hindi and other Indic | Devanagari's alphabet order mostly matches code-point order, but nukta letters (क़, फ़), anusvara and conjuncts need rules |
The lab's Hindi words sorted the same under C and hi-x-icu, because the chosen set didn't exercise those cases. Don't conclude that Indic sorting is "just code points": test with nukta letters and words that differ only by conjunct.
Options refine collation, expressed in BCP 47 -u- extensions:
| Option | Meaning | Example |
|---|---|---|
kn-true |
numeric: digit runs compare as numbers | und-u-kn-true |
ks-level1, level2 |
strength: ignore case (level 2) or case and accents (level 1) | und-u-ks-level2 |
kf-upper |
uppercase first among case variants | |
ka-shifted |
ignore punctuation and spaces at the first levels | |
co-phonebk |
a named variant | de-u-co-phonebk |
Case: mapping versus folding
Case operations are not simple table lookups:
- Language-specific mappings: in Turkish and Azerbaijani,
iuppercases toİandIlowercases toı. The lab:upper('istanbul')gaveISTANBULunderen-x-icuandİSTANBULundertr-x-icu;lower('ISTANBUL')gaveıstanbulunder Turkish. Code that uppercases identifiers with the user's locale has broken Turkish users' logins for decades; uppercase identifiers with a fixed locale (Locale.ROOTin Java and Kotlin). - Length changes:
ßuppercases toSS;fi(ligature) toFI. - Context: Greek capital Σ lowercases to
ςat the end of a word andσelsewhere. - Titlecase exists separately: the digraph
džtitlecases toDž.
Case mapping (upper, lower) is for display. Case folding (Unicode's CaseFolding.txt, Python's str.casefold()) is for comparison: it maps strings to a form where caseless equals are identical, including ß → ss. For robust caseless matching: normalise (NFC or NFKC), case-fold, then compare. For accent-insensitive matching as well, decompose (NFD) and strip combining marks, or use a collation at strength 1.
Locale-aware comparison in code
Every platform has a collator; use it for anything shown to people:
| Platform | API |
|---|---|
| JavaScript | new Intl.Collator('sv', {numeric: true, sensitivity: 'base'}).compare, or a.localeCompare(b, 'sv') |
| Java / Kotlin | java.text.Collator.getInstance(Locale.forLanguageTag("sv")); on Android, android.icu.text.Collator |
| Swift | a.compare(b, locale: Locale(identifier: "sv")), localizedStandardCompare (numeric, as Finder sorts) |
| Python | PyICU's Collator; the standard locale.strxfrm depends on the OS locale and is fragile in servers |
| PostgreSQL | ORDER BY name COLLATE "sv-x-icu" |
Two practical rules. Sort with the viewer's locale, not the server's: a Swedish user and a German user see different orders of the same data. And when sorting large lists, use sort keys (Collator.getCollationKey, strxfrm, Intl.Collator reused rather than created per comparison) because building collation weights is the expensive part.
Collation in databases
PostgreSQL
PostgreSQL has two collation providers:
- libc: uses the operating system's C library locales (
en_US.UTF-8). Order depends on the OS and its version. - ICU: uses the ICU library with CLDR data (
und-x-icu,sv-x-icu, or custom ones). Same order on every OS for the same ICU version.
You can set a collation for the database, a column, an index or a single expression:
CREATE COLLATION num_icu (provider = icu, locale = 'und-u-kn-true');
CREATE COLLATION ci_ai (provider = icu, locale = 'und-u-ks-level1', deterministic = false);
SELECT name FROM dishes ORDER BY name COLLATE "sv-x-icu";
SELECT * FROM users WHERE email = 'Ana@Example.com' COLLATE ci_ai;
Things to know:
- Indexes are built in a collation's order. An index on
nameservesORDER BY nameonly for the same collation.LIKE 'pan%'can use a B-tree index only withCcollation or atext_pattern_opsindex. - Nondeterministic collations (case- or accent-insensitive) make
=andUNIQUEwork caselessly, butLIKEand some operations are restricted and they're slower than deterministic ones. A common alternative for emails and usernames: store a normalised, case-folded key in its own column with a unique index. - Collation versions matter. When glibc 2.28 (2018) changed sort order for many strings, databases whose indexes were built with the old order returned wrong results and let duplicates past unique constraints until indexes were rebuilt. PostgreSQL records collation versions and warns on mismatch; after an OS or ICU upgrade, check
pg_collationversion warnings andREINDEXaffected indexes. Upgrading by logical replication or dump/restore rebuilds indexes automatically; streaming replicas on a different OS version do not.
Other databases
MySQL's utf8mb4_0900_ai_ci is accent- and case-insensitive by default (so 'é' = 'e' is true in a WHERE, often surprising). Note MySQL's old utf8 is 3-byte only and can't store emoji; always use utf8mb4. SQL Server and Oracle have their own collation names and options. Whatever the database, decide the collation per column deliberately.
Searching multilingual text
Search is matching under transformations. A typical analysis pipeline for each document and query:
- Normalise (NFKC) and case-fold.
- Tokenise into words. Spaces don't separate words in Thai, Lao, Khmer, Chinese and Japanese; these need dictionary-based segmenters (ICU's word break iterator, Kuromoji for Japanese). Indic scripts use spaces but have rich morphology.
- Fold accents for accent-insensitive matching (often wanted in French and Spanish search, less so in languages where accents distinguish words).
- Stem or lemmatise per language:
curries→curry. Stemmers are language-specific; a Hindi stemmer differs from an English one, and many languages have none. - Expand with synonyms and transliterations.
Transliteration matters in India above all: people type Hindi and Telugu words in Latin script ("paneer", "pesarattu", "biryani", "biriyani") as often as in native script. A dish named पनीर टिक्का should match paneer tikka. Options: store transliterated forms alongside the native name (ICU's Any-Latin transform or the IndicTrans tools generate them), add curated synonyms for popular items, and use fuzzy matching on the Latin form for spelling variants.
Tools: PostgreSQL full-text search has per-language configurations (to_tsvector('english', …)) but limited Indic support, plus unaccent and pg_trgm for fuzzy matching; Elasticsearch and OpenSearch have the ICU analysis plugin (icu_tokenizer, icu_folding, icu_transform) and language analysers including Hindi.
For semantic search (Volume 14), multilingual embedding models map "curd rice", "పెరుగు అన్నం" and "தயிர் சாதம்" near each other, which helps where lexical rules run out; combine both (hybrid search).
Common traps
- Sorting with
<or the database's defaultC/libc order in user-facing lists. lower(a) = lower(b)for caseless matching.- Uppercasing identifiers with the user's locale (the Turkish I problem).
- MySQL
utf8instead ofutf8mb4. - Upgrading the OS under a database without checking collation versions.
- Splitting on spaces to find words.
- Ignoring transliteration where users type in Latin script.
Lab: one table, many orders
Setup. PostgreSQL 16.15 on the lab machine, built with ICU, holding a one-column table of 18 names: dish and place names in English, German, French and Turkish, plus 10 idlis and 2 dosas. The script sorts with ORDER BY n COLLATE "<collation>", creates a numeric ICU collation (und-u-kn-true) and a nondeterministic case- and accent-insensitive one (und-u-ks-level1), and compares case mappings under English and Turkish ICU collations. A second table holds eight Hindi dish names. All results are real PostgreSQL output.
Results: sorting
| Collation | Order |
|---|---|
C |
10 idlis, 2 dosas, Apple, Istanbul, Ozone, Side, Zebra cake, Zucker, apple, eclair, side, zeera rice, Äpfel, Écrin, Österreich, éclair, İzmir, ılık |
und-x-icu |
10 idlis, 2 dosas, Äpfel, apple, Apple, eclair, éclair, Écrin, Istanbul, İzmir, ılık, Österreich, Ozone, side, Side, Zebra cake, zeera rice, Zucker |
de-x-icu |
identical to und-x-icu for this set |
sv-x-icu |
10 idlis, 2 dosas, apple, Apple, eclair, éclair, Écrin, Istanbul, İzmir, ılık, Ozone, side, Side, Zebra cake, zeera rice, Zucker, Äpfel, Österreich |
tr-x-icu |
10 idlis, 2 dosas, Äpfel, apple, Apple, eclair, éclair, Écrin, ılık, Istanbul, İzmir, Ozone, Österreich, side, Side, … |
Results: numbers, equality and case
| Test | Result |
|---|---|
und-x-icu on Order 2/9/10/100 |
Order 10, Order 100, Order 2, Order 9 |
numeric und-u-kn-true |
Order 2, Order 9, Order 10, Order 100 |
'eclair' = 'Éclair' |
ci_ai: true; lower(): false |
'CRÈME' = 'creme' |
ci_ai: true; lower(): false |
'straße' = 'STRASSE' |
ci_ai: true; lower(): false |
upper('istanbul') |
en: ISTANBUL; tr: İSTANBUL |
lower('ISTANBUL') |
en: istanbul; tr: ıstanbul |
Hindi names under C and hi-x-icu |
same order for this set |
What it shows
- Byte order is unusable for people: all capitals first, accented letters stranded at the end.
- Language tailorings change real results: Swedish moves Ä and Ö to the end; Turkish separates ı from I/İ.
- Default ICU is a good baseline when the viewer's language is unknown, and much better than
C. - Numeric collation fixes "Order 10 before Order 2" without changing the data.
- Proper caseless matching handles accents and expansions that
lower()can't. - Case mapping depends on language, which is why identifiers must be cased with a fixed locale.
- A small test set can hide differences (the Hindi result): test with the hard cases of each script.
Try it yourself
- Add
क़लम,कलम,फ़िरनीandफिरनीto the Hindi table and compareCwithhi-x-icu. - Create
CREATE COLLATION de_phone (provider = icu, locale = 'de-u-co-phonebk')and sortMüller, Mueller, Muller. - Put a
UNIQUEindex on an email column with theci_aicollation and try to insertAna@x.inandana@x.in. - Run
EXPLAINonWHERE name LIKE 'pan%'with the default collation, then with atext_pattern_opsindex. - In a browser console, sort
['Order 10','Order 2','Äpfel','apple','Zucker']withsort(), then withnew Intl.Collator('sv', {numeric: true}).compare.
Revision sheet: comparing, sorting and searching text
Key ideas
- Code-point order is for machines; people need locale-aware collation.
- The UCA compares base letters, then accents, then case; CLDR tailors it per language (Swedish ä after z, Turkish ı, Spanish ñ).
- Options: numeric (
kn), strength (ks), punctuation handling, named variants. - Case mapping is for display and is language-dependent; case folding (plus normalisation) is for comparison.
- Use the platform collator with the viewer's locale; reuse collators and sort keys.
- PostgreSQL: libc vs ICU providers; indexes follow a collation; nondeterministic collations for caseless equality; rebuild indexes after collation-library upgrades.
- MySQL: use
utf8mb4. - Search: normalise, fold, tokenise per language, stem, expand with synonyms and transliterations; hybrid with multilingual embeddings.
Numbers to remember
- glibc 2.28 (2018) changed sort order and silently invalidated text indexes.
- Collation levels: primary (letters), secondary (accents), tertiary (case).
Glossary
- Collation: rules for ordering and comparing strings.
- UCA / DUCET: Unicode Collation Algorithm and its default table.
- Tailoring: a language's changes to the default collation.
- Strength: which levels a comparison considers.
- Case folding: mapping for caseless comparison.
- Nondeterministic collation: one where different strings can compare equal.
- Transliteration: writing a word in another script (पनीर → paneer).
- Analyser: a search engine's pipeline of tokeniser and filters.