Full answer
sql
CREATE TABLE imports (id INTEGER PRIMARY KEY, qty TEXT);
INSERT INTO imports VALUES (1, '9'), (2, '10'), (3, '25');The query as written:
sql
SELECT id, qty FROM imports WHERE qty > 10 ORDER BY id;| id | qty |
|---|---|
| 1 | 9 |
| 3 | 25 |
The result contains id 1 ('9') and id 3 ('25'), so id 1 ('9') appears even though 9 is less than 10. The comparison ran as text, where '9' > '10'. When one side is a TEXT-affinity column and the other a literal, SQLite converts the literal to text before comparing.
A corrected version:
sql
SELECT id, qty FROM imports WHERE CAST(qty AS INTEGER) > 10 ORDER BY id;| id | qty |
|---|---|
| 3 | 25 |
With the cast, only 25 is greater than 10. The cast blocks index use on qty, so the lasting fix is a migration to an INTEGER column, with bad values rejected on import. PostgreSQL refuses to compare text with an integer without a cast, which surfaces the problem at once (described here, not run).
sql
CREATE TABLE imports (id INTEGER PRIMARY KEY, qty TEXT);
INSERT INTO imports VALUES (1, '9'), (2, '10'), (3, '25');
SELECT id, qty FROM imports WHERE qty > 10 ORDER BY id;
SELECT id, qty FROM imports WHERE CAST(qty AS INTEGER) > 10 ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- TEXT affinity makes literal comparisons textual
- Text order: '9' > '10'
- CAST fixes the query; the right column type fixes the data
- PostgreSQL requires explicit casts
Common mistakes
- Storing numbers as text from CSV imports
- Assuming SQLite compares the way the data looks
Follow-ups
- What are SQLite's five affinities?
- How would STRICT tables prevent this?
Tips
- Name the affinity rule