← Back to SQL, page 21

sql-0415 · Medium mid

In SQLite, what are MIN and MAX over a column holding 1, 'a' and 2.5?

MIN is 1 and MAX is 'a'. SQLite orders values across storage classes as NULL, then numbers (integers and reals together), then text, then blobs, so any text value is greater than any number.

Full answer
sql
CREATE TABLE mixed (v);
INSERT INTO mixed VALUES (1), ('a'), (2.5);
SELECT MIN(v) AS lo, MAX(v) AS hi, typeof(MAX(v)) AS hi_type FROM mixed;
lohihi_type
1atext

The column has no declared type, so each value keeps its own class. Among numbers, 1 is smaller than 2.5, and numbers rank below text, so MIN is 1 and MAX is the text 'a', reported with type text. The same cross-class ordering drives ORDER BY, which is why a numeric column polluted with a stray string sorts that string last. PostgreSQL cannot store mixed types in one column, so this situation does not arise there.

sql
CREATE TABLE mixed (v);
INSERT INTO mixed VALUES (1), ('a'), (2.5);
SELECT MIN(v) AS lo, MAX(v) AS hi, typeof(MAX(v)) AS hi_type FROM mixed;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Cross-class order: NULL < numbers < text < blob
  • Integers and reals compare numerically
  • Mixed columns sort surprisingly

Common mistakes

  • Assuming MAX on a numeric-looking column returns a number

Follow-ups

  • How would you find non-numeric values in such a column?
  • How would STRICT tables prevent this?

Tips

  • Recall the storage class order