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;| id | d |
|---|---|
| 2 | 2026-10-01 |
| 4 | 2026-11-2 |
| 3 | 2026-9-28 |
| 1 | 2026-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;| id | d | parsed |
|---|---|---|
| 1 | 2026-09-05 | 2026-09-05 |
| 3 | 2026-09-28 | 2026-09-28 |
| 2 | 2026-10-01 | 2026-10-01 |
| 4 | 2026-11-02 | 2026-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'