Full answer
sql
CREATE TABLE timeline (id INTEGER PRIMARY KEY, created_at TEXT);
INSERT INTO timeline VALUES (1,'2026-03-05 09:00'),(2,'2026-03-05T10:00'),(3,'2026-03-05 22:30'),(4,'2026-03-06 01:00');The query as written:
sql
SELECT id, created_at FROM timeline WHERE created_at <= '2026-03-05 23:59' ORDER BY id;| id | created_at |
|---|---|
| 1 | 2026-03-05 09:00 |
| 3 | 2026-03-05 22:30 |
Row 2 happened on 5 March at 10:00, well before the cut-off, yet it is missing: after the matching date prefix, the comparison reaches the separator, and 'T' sorts after the space in the filter value.
A corrected version:
sql
SELECT id, created_at FROM timeline WHERE datetime(created_at) <= datetime('2026-03-05 23:59') ORDER BY id;| id | created_at |
|---|---|
| 1 | 2026-03-05 09:00 |
| 2 | 2026-03-05T10:00 |
| 3 | 2026-03-05 22:30 |
datetime() parses both separators into a canonical 'YYYY-MM-DD HH:MM:SS' string, so row 2 is included and only the 6 March row is excluded. The deeper fix is to store one format, ideally a native timestamp type in PostgreSQL, and reject others at insert time with a CHECK constraint. Wrapping the column in a function also prevents plain index use, which is another reason to normalise data rather than the query.
sql
CREATE TABLE timeline (id INTEGER PRIMARY KEY, created_at TEXT);
INSERT INTO timeline VALUES (1,'2026-03-05 09:00'),(2,'2026-03-05T10:00'),(3,'2026-03-05 22:30'),(4,'2026-03-06 01:00');
SELECT id, created_at FROM timeline WHERE created_at <= '2026-03-05 23:59' ORDER BY id;
SELECT id, created_at FROM timeline WHERE datetime(created_at) <= datetime('2026-03-05 23:59') ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Text timestamps compare character by character
- Space sorts before T
- datetime() normalises both forms
- Normalise at write time
- Functions on the column block plain indexes
Common mistakes
- Mixing separators in text timestamps
- Fixing the query while leaving the data inconsistent
Follow-ups
- How would you add a CHECK that enforces one format?
- How do PostgreSQL timestamp types avoid this class of bug?
Tips
- Compare the separator characters