Full answer
sql
SELECT 'abc' < 'abd' AS a, 'Z' < 'a' AS b, 'apple' < 'Apple' AS c, 'apple' < 'Apple' COLLATE NOCASE AS d;| a | b | c | d |
|---|---|---|---|
| 1 | 1 | 0 | 0 |
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