Full answer
sql
SELECT 10 < '9' AS num_vs_text, '10' < '9' AS text_vs_text, 10 < 9 AS num_vs_num;| num_vs_text | text_vs_text | num_vs_num |
|---|---|---|
| 1 | 1 | 0 |
The literals have no affinity, so 10 versus '9' compares a number with text, and every number sorts before every text value. Between two text values, '10' < '9' because '1' comes before '9'.
When one side is a column with INTEGER affinity, SQLite applies the affinity to the text literal first:
sql
CREATE TABLE n (x INTEGER);
INSERT INTO n VALUES (10);
SELECT x < '9' AS col_vs_text FROM n;| col_vs_text |
|---|
| 0 |
The column comparison converts '9' to 9, so 10 is not less than it. Mixed storage classes in one column produce mixed sort orders:
sql
CREATE TABLE m (x);
INSERT INTO m VALUES (10), ('9'), (2), ('abc'), (NULL);
SELECT x, typeof(x) AS t FROM m ORDER BY x;| x | t |
|---|---|
| NULL | null |
| 2 | integer |
| 10 | integer |
| 9 | text |
| abc | text |
sql
SELECT 10 < '9' AS num_vs_text, '10' < '9' AS text_vs_text, 10 < 9 AS num_vs_num;
CREATE TABLE n (x INTEGER);
INSERT INTO n VALUES (10);
SELECT x < '9' AS col_vs_text FROM n;
CREATE TABLE m (x);
INSERT INTO m VALUES (10), ('9'), (2), ('abc'), (NULL);
SELECT x, typeof(x) AS t FROM m ORDER BY x;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Storage class order: NULL, numbers, text, blob
- Text compares as text, so '10' < '9'
- Column affinity can convert the other operand
- Mixed types in one column sort in groups
Common mistakes
- Storing numbers as text and sorting them
- Assuming literal comparisons behave like column comparisons
Follow-ups
- How would you sort a text column numerically?
- What does PostgreSQL do with 10 < '9'?
Tips
- Use typeof() on the column to diagnose