← Back to SQL, page 25

sql-0484 · Medium mid

Predict SELECT max('apple', 'Banana') and min(3, NULL) in SQLite.

max('apple', 'Banana') returns 'apple', because comparison is by bytes and lowercase 'a' (97) is greater than uppercase 'B' (66). min(3, NULL) returns NULL, because SQLite's multi-argument min and max return NULL if any argument is NULL, unlike the aggregate versions, which ignore NULLs.

Full answer
sql
SELECT max('apple', 'Banana') AS max_text, min(3, NULL) AS min_with_null, max(3, 5, 4) AS max_numbers;
max_textmin_with_nullmax_numbers
appleNULL5

With two or more arguments, min() and max() are scalar functions. They compare with the usual rules, so text uses the BINARY collation unless an argument carries another collation. Any NULL argument makes the result NULL, which differs from aggregate MIN and MAX, which skip NULLs. PostgreSQL's GREATEST and LEAST ignore NULLs and return NULL only when all arguments are NULL (not run here), so the same intent gives different results across engines. Wrap arguments in COALESCE when NULL should be ignored in SQLite.

sql
SELECT max('apple', 'Banana') AS max_text, min(3, NULL) AS min_with_null, max(3, 5, 4) AS max_numbers;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Scalar min and max return NULL if any argument is NULL
  • Aggregate MIN and MAX ignore NULLs
  • Text compares by bytes by default
  • GREATEST and LEAST in PostgreSQL ignore NULLs

Common mistakes

  • Assuming scalar and aggregate forms treat NULL alike

Follow-ups

  • How would you take the larger of two nullable columns in SQLite?
  • How would you compare case-insensitively?

Tips

  • Spot the NULL argument