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.

SqlData Fetching

Code

snippet
-- 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

FAQ

Which tables appear in this script?
The references are `customers`.