← Back to SQL, page 17

sql-0339 · Hard senior

A filter on a text column of quantities returns 9 as greater than 10. Explain the SQLite behaviour and fix it.

The column has TEXT affinity, so SQLite applies text affinity to the numeric literal and compares strings: '9' > '10' because '9' sorts after '1'. Cast the column with CAST(qty AS INTEGER), or better, store numbers in an INTEGER column.

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;
idqty
19
325

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;
idqty
325

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