← Back to SQL, page 8

sql-0160 · Medium mid

Dates were stored as text in the format '5/3/2026'. Why does ORDER BY and a range filter on that column give wrong results?

Text compares character by character, so '10/1/2026' sorts before '5/3/2026' because '1' comes before '5'. Ranges fail for the same reason. Convert the column to ISO 'YYYY-MM-DD' once, then sorting and comparisons work as dates.

Full answer
sql
WITH t(d) AS (VALUES ('5/3/2026'), ('10/1/2026'), ('12/25/2025'))
SELECT d, d < '5/3/2026' AS before_may3_as_text FROM t ORDER BY d;
dbefore_may3_as_text
10/1/20261
12/25/20251
5/3/20260

The order is alphabetical, not chronological. The filter is also wrong: as text, '12/25/2025' is less than '5/3/2026', so a December 2025 date passes a filter meant for 2026.

Convert with string functions into zero-padded ISO text:

sql
WITH t(d) AS (VALUES ('5/3/2026'), ('10/1/2026'), ('12/25/2025')),
 p AS (SELECT d, INSTR(d, '/') AS s1 FROM t),
 q AS (SELECT d, s1, s1 + INSTR(SUBSTR(d, s1 + 1), '/') AS s2 FROM p)
SELECT d,
       SUBSTR(d, s2 + 1) || '-' || printf('%02d', SUBSTR(d, 1, s1 - 1)) || '-' || printf('%02d', SUBSTR(d, s1 + 1, s2 - s1 - 1)) AS iso
FROM q ORDER BY iso;
diso
12/25/20252025-12-25
5/3/20262026-05-03
10/1/20262026-10-01

The conversion assumes month/day/year; a mixed column where some rows are day/month needs a source-by-source rule. After converting, add CHECK (d = date(d)) in SQLite so only valid ISO dates can be stored.

sql
WITH t(d) AS (VALUES ('5/3/2026'), ('10/1/2026'), ('12/25/2025'))
SELECT d, d < '5/3/2026' AS before_may3_as_text FROM t ORDER BY d;

WITH t(d) AS (VALUES ('5/3/2026'), ('10/1/2026'), ('12/25/2025')),
 p AS (SELECT d, INSTR(d, '/') AS s1 FROM t),
 q AS (SELECT d, s1, s1 + INSTR(SUBSTR(d, s1 + 1), '/') AS s2 FROM p)
SELECT d,
       SUBSTR(d, s2 + 1) || '-' || printf('%02d', SUBSTR(d, 1, s1 - 1)) || '-' || printf('%02d', SUBSTR(d, s1 + 1, s2 - s1 - 1)) AS iso
FROM q ORDER BY iso;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Non-ISO text dates sort as strings
  • Range filters on them give wrong answers
  • Convert once to YYYY-MM-DD
  • A CHECK with date() keeps the column valid

Common mistakes

  • Sorting display-formatted dates
  • Guessing day/month order without checking the source

Follow-ups

  • How would you detect rows that are not valid dates?
  • How would you convert day/month data from another source?

Tips

  • Show one wrong comparison concretely