Sub topic 8
Date and timestamp ranges: avoiding the end-of-day trap
This chapter covers filtering on date and timestamp columns. It assumes you can write a basic SELECT, use comparison operators and AND, and know that BETWEEN includes both endpoints. The main point is that BETWEEN fits whole numbers well but often misses rows when the column holds a time of day.
Why dates behave differently from numbers
For a whole-number column, BETWEEN 10 AND 20 is clear. Both 10 and 20 are included, and no value lies between 20 and 21.
A date or timestamp column is different. Its type decides how much of the day it stores:
| Column type | What it stores | Example value |
|---|---|---|
| `DATE` | A calendar day only (in Oracle, `DATE` also carries a time) | `2026-03-31` |
| `TIMESTAMP` | A day plus a time, often with fractions of a second | `2026-03-31 17:45:12.250` |
| `TIMESTAMP WITH TIME ZONE` | A timestamp tied to an offset or zone | `2026-03-31 17:45:12+00` |
When you compare a timestamp to a bare date literal such as '2026-03-31', the database converts the literal to a timestamp. The usual conversion sets the time to midnight: 2026-03-31 00:00:00. This conversion is the source of the end-of-day trap.
The end-of-day trap
Suppose you want every order placed in March 2026, and you write this:
SELECT id, created_at
FROM orders
WHERE created_at BETWEEN '2026-03-01' AND '2026-03-31';BETWEEN is shorthand for created_at >= '2026-03-01' AND created_at <= '2026-03-31'. With a TIMESTAMP column, the upper bound becomes 2026-03-31 00:00:00. An order created at 2026-03-31 09:30:00 is later than that bound, so the query drops it. Only orders at exactly midnight on March 31 survive. You lose almost the whole last day, and no error tells you.
The query looks correct and works on test data that happens to hold only midnight values. It fails once real data with times arrives, so the bug often shows up in production.
The fix: half-open ranges
A half-open range includes the start and excludes the end. You write it as >= on the lower bound and < on the upper bound. To cover all of March, the upper bound is the first instant of April:
SELECT id, created_at
FROM orders
WHERE created_at >= '2026-03-01'
AND created_at < '2026-04-01';This catches every timestamp from midnight on March 1 up to, but not including, midnight on April 1. That covers late March 31, whatever the time precision.
Half-open ranges have these advantages:
- They need no knowledge of precision. The same query works whether the column stores seconds, milliseconds, or microseconds.
- Adjacent ranges do not overlap. The end of one month is the start of the next, so a row never counts twice and never falls in a gap.
- You can compute the end bound simply. It is just "the start plus one unit", which is easier than "the last representable moment".
Why "23:59:59" is not a fix
A common workaround is to write the end of the day by hand:
SELECT id, created_at
FROM orders
WHERE created_at BETWEEN '2026-03-01 00:00:00' AND '2026-03-31 23:59:59';This is better, but it still has a gap. If the column stores fractions of a second, a row at 2026-03-31 23:59:59.500 is later than 23:59:59.000 and is excluded. Writing 23:59:59.999 only moves the gap. Some systems round such a literal up to the next day, so you cannot trust it. The precision of the column varies by database and by column definition, so a fix that depends on it is fragile. The half-open range avoids the question.
Filtering a single day
To get all rows from one day, use the same pattern with a one-day window:
SELECT id, created_at
FROM orders
WHERE created_at >= '2026-03-15'
AND created_at < '2026-03-16';You may be tempted to cast the column to a date instead, for example WHERE CAST(created_at AS DATE) = '2026-03-15'. This is correct, but it wraps the column in a function. In most databases that stops the optimizer from using an ordinary index on created_at, because the index is sorted by the raw values, not by the cast values. The half-open form keeps the column bare, so an index can be used. The later chapter on indexes covers this in more detail.
Computing the boundaries with date arithmetic
Hard-coded literals are fine for fixed reports. For rolling windows, compute the bounds. Date functions differ between databases, so the examples below show common forms.
PostgreSQL, with the current month:
SELECT id, created_at
FROM orders
WHERE created_at >= date_trunc('month', CURRENT_DATE)
AND created_at < date_trunc('month', CURRENT_DATE) + INTERVAL '1 month';MySQL, with the last 7 days including today:
SELECT id, created_at
FROM orders
WHERE created_at >= CURRENT_DATE - INTERVAL 6 DAY
AND created_at < CURRENT_DATE + INTERVAL 1 DAY;In both queries the upper bound is the first moment after the period, and the column is left untouched. The syntax for intervals and truncation is not portable. SQL Server uses DATEADD and DATETRUNC (the latter in recent versions), and SQLite uses date() with modifiers. The shape of the filter stays the same everywhere.
Date literals and portability
How you write the literal matters, because an ambiguous format can be read differently by different settings.
- Use the ISO 8601 form
YYYY-MM-DD, orYYYY-MM-DD HH:MM:SSfor timestamps. It cannot be confused with day-first or month-first formats. - The standard also defines typed literals, such as
DATE '2026-03-01'andTIMESTAMP '2026-03-01 00:00:00'. These state the type explicitly and are accepted by PostgreSQL, MySQL, and Oracle. Oracle requires the typed form orTO_DATEin many places, because it does not reliably convert a plain string. - In SQL Server, the plain
YYYY-MM-DDform is safe fordateanddatetime2. For the olderdatetimetype, the unseparated formYYYYMMDDis the only one that is always read the same way regardless of language settings.
Here is the March query with typed literals:
SELECT id, created_at
FROM orders
WHERE created_at >= TIMESTAMP '2026-03-01 00:00:00'
AND created_at < TIMESTAMP '2026-04-01 00:00:00';Time zones
If the column is TIMESTAMP WITH TIME ZONE, "March" depends on whose March you mean. A literal without an offset is interpreted in the session's time zone, so the same query can return different rows for sessions with different settings. Two habits reduce surprises:
- Decide which time zone defines your reporting period, and state it in the literal, for example
'2026-03-01 00:00:00+00'. - Store timestamps in UTC and convert only for display.
Half-open ranges still apply. The only change is that the boundaries must be in the zone you intend.
When BETWEEN on dates is acceptable
BETWEEN is safe on dates in one situation: the column is a pure DATE type with no time component, and the database does not attach a time to it. Then BETWEEN '2026-03-01' AND '2026-03-31' correctly covers March, because every value is exactly midnight.
Even then, the half-open form is a better habit, for three reasons. The column type may change later from DATE to TIMESTAMP and silently break the filter. Oracle's DATE includes a time, so the trap applies there. And one consistent style is easier to review than a mix of two.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| `BETWEEN '2026-03-01' AND '2026-03-31'` on a timestamp | Drops most of March 31 | Use `< '2026-04-01'` |
| `BETWEEN ... AND '... 23:59:59'` | Drops fractional seconds late on the last day | Use a half-open range |
| `CAST(created_at AS DATE) = ...` on a large table | Often prevents index use | Compare the bare column to a day window |
| Using `<= '2026-04-01'` as the end | Includes rows at exactly midnight April 1 | Use `<` |
| Literal in a local format such as `03/04/2026` | Read as March 4 or April 3 depending on settings | Use ISO 8601 |
Checking your query
A quick test catches this bug. Insert rows at the boundaries and see which the filter returns:
CREATE TABLE orders_test (
id INTEGER PRIMARY KEY,
created_at TIMESTAMP NOT NULL
);
INSERT INTO orders_test (id, created_at) VALUES
(1, '2026-02-28 23:59:59'),
(2, '2026-03-01 00:00:00'),
(3, '2026-03-31 09:30:00'),
(4, '2026-03-31 23:59:59.500'),
(5, '2026-04-01 00:00:00');
SELECT id
FROM orders_test
WHERE created_at >= '2026-03-01'
AND created_at < '2026-04-01'
ORDER BY id;The result is rows 2, 3, and 4. Row 1 is before the range, and row 5 is the first moment of April. If you replace the filter with BETWEEN '2026-03-01' AND '2026-03-31', only row 2 remains, which shows the trap directly.
Exercise
A table events has a TIMESTAMP column happened_at. Write a query that returns all events from 12 June 2026, and explain why WHERE happened_at BETWEEN '2026-06-12' AND '2026-06-12' is wrong.
Show answer
Use a one-day half-open range: SELECT id, happened_at FROM events WHERE happened_at >= '2026-06-12' AND happened_at < '2026-06-13';. The BETWEEN version is equivalent to happened_at >= '2026-06-12 00:00:00' AND happened_at <= '2026-06-12 00:00:00', so it returns only events at exactly midnight and drops the rest of the day.
Exercise
A report uses created_at BETWEEN '2026-01-01' AND '2026-01-31 23:59:59'. Describe one row that it misses, and rewrite the filter.
Show answer
A row with created_at equal to 2026-01-31 23:59:59.750 is later than the upper bound and is missed when the column stores fractional seconds. The rewrite is created_at >= '2026-01-01' AND created_at < '2026-02-01'.