COLLATE Explicit Sort Order
Control string comparison per column, per query, and per index with COLLATE, so the same names sort differently per language and indexes stay usable.
Code
-- COLLATE 决定字符串比较与排序规则:可按列、按查询、按索引指定
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL COLLATE "de_DE",
city text NOT NULL
);
-- 查询级 COLLATE 覆盖列定义:同一份数据按不同语言排序
SELECT name FROM customers ORDER BY name COLLATE "sv_SE";
-- C locale 按字节序:大小写混排时大写在前,结果完全确定
SELECT name FROM customers ORDER BY name COLLATE "C";
-- 索引的排序规则是索引属性:必须与查询使用的 COLLATE 匹配才可用
CREATE INDEX customers_name_sv ON customers (name COLLATE "sv_SE");How it works
Several statements share this file — SELECT / CREATE, with customers among the objects involved.
Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Run the statement against the customers table.
Statements that matter
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL COLLATE "de_DE",
city text NOT NULL
);
CREATE INDEX customers_name_sv ON customers (name COLLATE "sv_SE");
SELECT name FROM customers ORDER BY name COLLATE "sv_SE";
Interactive Tools for This Topic
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.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.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.
FAQ
- Which tables appear in this script?
- The references are `customers`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.