SQL: ORDER BY on a column with a mixed case or accent needs a collation

Sort order comes from the column's collation, not from ASCII. The same query returns a different order on a different database unless the collation is explicit.

Code
SELECT name FROM users ORDER BY name;

-- Case-insensitive comparison and ordering:
SELECT name FROM users ORDER BY name COLLATE "en_US";
SELECT name FROM users WHERE LOWER(name) = 'ann';

-- PostgreSQL 12+ non-deterministic collation, for a case-insensitive column:
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2',
                     deterministic = false);
ALTER TABLE users ALTER COLUMN name TYPE text COLLATE ci;
Output
C collation (byte order):   Ann, Bob, Zed, ann, bob
en_US collation:            Ann, ann, Bob, bob, Zed

-- A database created with LC_COLLATE=C sorts uppercase before all lowercase.
-- This is why a list looks correctly alphabetised locally and wrong in
-- production, or the reverse.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-25