Full answer
sql
CREATE TABLE web_orders (id INTEGER PRIMARY KEY, ts TEXT NOT NULL);
INSERT INTO web_orders VALUES (1, '2026-03-01 09:00'), (2, '2026-03-05 12:00'), (3, '2026-03-09 14:30'), (4, '2026-03-10 08:00');The query as written:
sql
SELECT id, ts FROM web_orders WHERE ts BETWEEN '2026-03-01' AND '2026-03-09' ORDER BY id;| id | ts |
|---|---|
| 1 | 2026-03-01 09:00 |
| 2 | 2026-03-05 12:00 |
Order 3 is missing. The upper bound '2026-03-09' is the very start of that day as text, and any time on that day compares greater than it. The same problem appears in PostgreSQL with timestamp columns, where the date literal means midnight.
A corrected version:
sql
SELECT id, ts FROM web_orders WHERE ts >= '2026-03-01' AND ts < '2026-03-10' ORDER BY id;| id | ts |
|---|---|
| 1 | 2026-03-01 09:00 |
| 2 | 2026-03-05 12:00 |
| 3 | 2026-03-09 14:30 |
The half-open range includes all of March 9 and nothing from March 10, whatever the time precision. It also lets an index on ts be used, unlike wrapping the column in date(ts).
sql
CREATE TABLE web_orders (id INTEGER PRIMARY KEY, ts TEXT NOT NULL);
INSERT INTO web_orders VALUES (1, '2026-03-01 09:00'), (2, '2026-03-05 12:00'), (3, '2026-03-09 14:30'), (4, '2026-03-10 08:00');
SELECT id, ts FROM web_orders WHERE ts BETWEEN '2026-03-01' AND '2026-03-09' ORDER BY id;
SELECT id, ts FROM web_orders WHERE ts >= '2026-03-01' AND ts < '2026-03-10' ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- BETWEEN is inclusive but a date bound means midnight
- Use >= start AND < next day
- Half-open ranges are index friendly
Common mistakes
- Writing '2026-03-09 23:59:59', which misses fractional seconds
- Wrapping the column in date() and losing index use
Follow-ups
- How would you query a whole month?
- What changes if timestamps are stored in UTC?
Tips
- State the half-open rule