← Back to SQL, page 9

sql-0171 · Medium mid

In SQLite, how do values of different storage classes compare, such as 10 < '9' or 10 < 9?

Without a column affinity involved, SQLite orders storage classes as NULL < numbers < text < blob, so the integer 10 is less than any text, including '9'. Numbers compare numerically and text compares by collation. Comparing a column with a numeric affinity to text converts the text first, which changes the result.

Full answer
sql
SELECT 10 < '9' AS num_vs_text, '10' < '9' AS text_vs_text, 10 < 9 AS num_vs_num;
num_vs_texttext_vs_textnum_vs_num
110

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;
xt
NULLnull
2integer
10integer
9text
abctext
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