← Back to SQL, page 23

sql-0447 · Medium mid

Dates stored as '2026-9-5' and '2026-10-01' sort in the wrong order. Fix the data and the query.

Without zero padding, text comparison puts '2026-10-01' before '2026-9-5' because '1' sorts before '9'. Normalise the values to ISO 'YYYY-MM-DD' with zero padding (for example with printf and string splitting), then store only that format, checked by a CHECK constraint.

Full answer
sql
CREATE TABLE visits (id INTEGER PRIMARY KEY, d TEXT);
INSERT INTO visits VALUES (1, '2026-9-5'), (2, '2026-10-01'), (3, '2026-9-28'), (4, '2026-11-2');

The query as written:

sql
SELECT id, d FROM visits ORDER BY d;
idd
22026-10-01
42026-11-2
32026-9-28
12026-9-5

Text sorts character by character: after '2026-', the '1' of October and November comes before the '9' of September, so the months appear out of order. Date functions also fail on such values: date('2026-9-5') returns NULL because SQLite's date functions require two-digit months and days.

A corrected version:

sql
UPDATE visits SET d = printf('%04d-%02d-%02d',
  CAST(substr(d, 1, 4) AS INTEGER),
  CAST(substr(d, 6, instr(substr(d, 6), '-') - 1) AS INTEGER),
  CAST(substr(substr(d, 6), instr(substr(d, 6), '-') + 1) AS INTEGER));
SELECT id, d, date(d) AS parsed FROM visits ORDER BY d;
iddparsed
12026-09-052026-09-05
32026-09-282026-09-28
22026-10-012026-10-01
42026-11-022026-11-02

The UPDATE splits each value at the dashes and rebuilds it with zero padding, so sorting and date() both work, as the parsed column confirms. Adding CHECK (d = date(d)) to the table rejects badly formatted values in future, since date() returns NULL or a different string for them.

sql
CREATE TABLE visits (id INTEGER PRIMARY KEY, d TEXT);
INSERT INTO visits VALUES (1, '2026-9-5'), (2, '2026-10-01'), (3, '2026-9-28'), (4, '2026-11-2');

SELECT id, d FROM visits ORDER BY d;

UPDATE visits SET d = printf('%04d-%02d-%02d',
  CAST(substr(d, 1, 4) AS INTEGER),
  CAST(substr(d, 6, instr(substr(d, 6), '-') - 1) AS INTEGER),
  CAST(substr(substr(d, 6), instr(substr(d, 6), '-') + 1) AS INTEGER));
SELECT id, d, date(d) AS parsed FROM visits ORDER BY d;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Unpadded dates sort wrongly as text
  • SQLite date functions need ISO format
  • Normalise with printf
  • CHECK (d = date(d)) enforces the format

Common mistakes

  • Sorting by a date stored in local formats
  • Fixing only the query and leaving bad data

Follow-ups

  • How would you parse DD/MM/YYYY values?
  • Why does ISO format sort correctly?

Tips

  • Show why '1' sorts before '9'