← Back to SQL, page 21

sql-0408 · Easy fresher

Predict the output of comparing 'Z' < 'a' and 'apple' < 'Apple' in SQLite.

'Z' < 'a' is 1 and 'apple' < 'Apple' is 0. SQLite's default BINARY collation compares bytes, and every uppercase ASCII letter has a lower code than every lowercase one, so uppercase sorts first. Use COLLATE NOCASE or lower() for case-insensitive comparisons.

Full answer
sql
SELECT 'abc' < 'abd' AS a, 'Z' < 'a' AS b, 'apple' < 'Apple' AS c, 'apple' < 'Apple' COLLATE NOCASE AS d;
abcd
1100

The first comparison differs at the third character, where 'c' comes before 'd', so it is 1. 'Z' is byte 90 and 'a' is byte 97, so 'Z' < 'a' is 1. 'apple' starts with byte 97 and 'Apple' with 65, so 'apple' is larger and the third result is 0. With NOCASE the two words are equal, so 'less than' is 0 as well. PostgreSQL's result depends on the database collation; with a linguistic locale such as en_US, lowercase and uppercase interleave and 'Z' < 'a' is false (PostgreSQL behaviour stated, not run here).

sql
SELECT 'abc' < 'abd' AS a, 'Z' < 'a' AS b, 'apple' < 'Apple' AS c, 'apple' < 'Apple' COLLATE NOCASE AS d;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • BINARY collation compares bytes
  • Uppercase ASCII sorts before lowercase
  • NOCASE folds ASCII case
  • PostgreSQL depends on the collation

Common mistakes

  • Expecting dictionary order from byte comparison

Follow-ups

  • How does NOCASE handle non-ASCII letters?
  • How would you sort names case-insensitively?

Tips

  • Think in character codes