← Back to SQL, page 8

sql-0149 · Medium mid

Does 'apple' < 'Banana' evaluate to true? How does collation affect string comparison and sorting?

In SQLite's default BINARY collation it is false, because uppercase letters have lower byte values than lowercase ones, so 'B' sorts before 'a'. With COLLATE NOCASE it is true. PostgreSQL uses the database's locale collation, which usually sorts case-insensitively first, but the "C" collation behaves like bytes.

Full answer
sql
SELECT 'apple' < 'Banana' AS binary_cmp, 'apple' < 'Banana' COLLATE NOCASE AS nocase_cmp;
binary_cmpnocase_cmp
01

SQLite compares bytes by default: B (66) is less than a (97), so 'apple' is not less than 'Banana'. NOCASE folds ASCII case before comparing.

Sorting shows the same effect:

sql
WITH w(word) AS (VALUES ('banana'), ('Apple'), ('cherry'), ('Date'))
SELECT group_concat(word, ',') AS binary_order FROM (SELECT word FROM w ORDER BY word)
UNION ALL
SELECT group_concat(word, ',') FROM (SELECT word FROM w ORDER BY word COLLATE NOCASE, word);
binary_order
Apple,Date,banana,cherry
Apple,banana,cherry,Date

PostgreSQL with the C collation sorts by bytes, while a linguistic collation such as und-x-icu, if available, sorts alphabetically:

sql
SELECT string_agg(word, ',' ORDER BY word COLLATE "C") AS c_order,
       string_agg(word, ',' ORDER BY word COLLATE "und-x-icu") AS icu_order
FROM (VALUES ('banana'), ('Apple'), ('cherry'), ('Date')) AS w(word);
c_ordericu_order
Apple,Date,banana,cherryApple,banana,cherry,Date

The practical rule: specify a collation where order matters to users, and do not assume test results on one engine will match production on another.

sql
SELECT 'apple' < 'Banana' AS binary_cmp, 'apple' < 'Banana' COLLATE NOCASE AS nocase_cmp;

WITH w(word) AS (VALUES ('banana'), ('Apple'), ('cherry'), ('Date'))
SELECT group_concat(word, ',') AS binary_order FROM (SELECT word FROM w ORDER BY word)
UNION ALL
SELECT group_concat(word, ',') FROM (SELECT word FROM w ORDER BY word COLLATE NOCASE, word);

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Collation decides string comparison and sort order
  • SQLite's default BINARY puts uppercase before lowercase
  • COLLATE NOCASE ignores ASCII case
  • PostgreSQL uses locale collations; "C" sorts by bytes

Common mistakes

  • Assuming alphabetical order is the same on every engine
  • Mixing case in user-facing lists sorted with a binary collation

Follow-ups

  • How would you make a column case-insensitive by default in SQLite?
  • Can collation affect index use?

Tips

  • Use the byte values to explain the result