Video in progress
Why doesn't `created_at BETWEEN '2026-01-01' AND '2026-01-31'` show the orders from the last day of January?
If created_at is a timestamp, '2026-01-31' really means January 31 at 00:00:00, so the rest of that day falls outside the range. The right way is a half-open range: >= '2026-01-01' AND < '2026-02-01'.
📖 Answer
BETWEEN includes both bounds, but when a date literal is converted to a timestamp, its time part is zero:
-- an order from January 31 at 14:20 doesn't land here
SELECT * FROM orders
WHERE created_at BETWEEN '2026-01-01' AND '2026-01-31';
Many people say "then I'll write '2026-01-31 23:59:59'". That's wrong too: a row at 23:59:59.500 is still left out, because PostgreSQL stores microseconds.
The correct way to write it:
SELECT * FROM orders
WHERE created_at >= '2026-01-01'
AND created_at < '2026-02-01';
This form also works well with an index. WHERE created_at::date = '2026-01-31' gives the right result too, but because there is a cast on the column, a regular index isn't used.
The same rule applies in Java: from is inclusive, to is exclusive. If a LocalDate comes in, I pass to.plusDays(1).atStartOfDay(). With timestamptz you also have to say which time zone the "day" is in: January 1 in Tashkent starts at 19:00 on December 31 in UTC.
Sign up to mark studied questions and save your progress.