Sub topic 12
Querying time ranges with half-open intervals
This chapter assumes you can write basic SELECT ... WHERE queries and that you know what timestamptz stores and how the session TimeZone setting affects it. It also assumes you have used AT TIME ZONE and date_trunc. Here you will apply them to the most common reporting task: selecting the rows that fall within a period such as a day, a month, or a billing window.
Why BETWEEN is the wrong tool
BETWEEN a AND b is inclusive at both ends. For timestamps this causes two bugs. Both come from the fact that a timestamptz has microsecond precision.
The first bug is the "end of day" hack, where you write 23:59:59 as the upper bound. A row at 23:59:59.5 is silently dropped. The second bug is the opposite. If you write BETWEEN '2024-06-01' AND '2024-07-01', rows at exactly midnight on July 1 appear in the June report and again in the July report.
Run this setup to see both:
SET TimeZone = 'UTC';
CREATE TABLE page_view (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
viewed_at timestamptz NOT NULL
);
INSERT INTO page_view (viewed_at) VALUES
('2024-05-31 23:59:59.999999+00'),
('2024-06-01 00:00:00+00'),
('2024-06-30 23:59:59.999999+00'),
('2024-07-01 00:00:00+00');
-- Inclusive bounds with the "23:59:59" hack
SELECT count(*) FROM page_view
WHERE viewed_at BETWEEN '2024-06-01 00:00:00' AND '2024-06-30 23:59:59';
-- 1 (misses the row at 23:59:59.999999)
-- Half-open range
SELECT count(*) FROM page_view
WHERE viewed_at >= '2024-06-01 00:00:00'
AND viewed_at < '2024-07-01 00:00:00';
-- 2The correct June count is 2. The half-open query returns it, and the BETWEEN query does not.
The half-open rule
A half-open interval includes its start and excludes its end. Mathematicians write it [start, end). In SQL you write >= start AND < end.
Use this form for every time range, for four reasons:
- The end of one period is exactly the start of the next, so periods tile with no gaps and no overlaps.
- You never need to know the precision of the column. It works the same for
date,timestamp(0), andtimestamptz(6). - To find the end of a period, add one unit to its start. You never subtract a tick.
- Adjacent ranges can be checked for correctness by comparing boundary values for equality.
Building the boundaries
Do not type the end bound by hand. Compute it from the start so that month lengths and leap years are handled for you.
SET TimeZone = 'UTC';
SELECT date_trunc('month', TIMESTAMPTZ '2024-06-15 12:00:00+00') AS month_start,
date_trunc('month', TIMESTAMPTZ '2024-06-15 12:00:00+00')
+ interval '1 month' AS next_month_start;
-- month_start: 2024-06-01 00:00:00+00
-- next_month_start: 2024-07-01 00:00:00+00This works well when your "month" is a UTC month. For a "month" in another zone, the safest approach is to do the calendar arithmetic on a plain timestamp, then convert each boundary to an instant. Calendar arithmetic on a plain timestamp does not depend on the session TimeZone.
WITH bounds AS (
SELECT TIMESTAMP '2024-06-01 00:00' AT TIME ZONE 'America/New_York' AS lo,
(TIMESTAMP '2024-06-01 00:00' + interval '1 month')
AT TIME ZONE 'America/New_York' AS hi
)
SELECT p.*
FROM page_view AS p, bounds AS b
WHERE p.viewed_at >= b.lo
AND p.viewed_at < b.hi;Remember from the AT TIME ZONE chapter that a plain timestamp on the left produces a timestamptz. Both lo and hi are therefore instants, and the comparison against a timestamptz column involves no further conversion.
Local days are not always 24 hours
Once you filter by local calendar day, the length of the range varies. On 2024-03-10 in New York the clocks jump from 02:00 to 03:00, so that local day is 23 hours long. The half-open pattern handles this without special cases, because the next local midnight is the end bound.
SET TimeZone = 'UTC';
SELECT (TIMESTAMP '2024-03-11 00:00' AT TIME ZONE 'America/New_York')
- (TIMESTAMP '2024-03-10 00:00' AT TIME ZONE 'America/New_York') AS day_length;
-- 23:00:00A query that assumed start + interval '24 hours' would include the first hour of March 11 in the March 10 report. In autumn, when a local day has 25 hours, the same assumption would drop an hour. Compute the end as "next local midnight", not "start plus 24 hours".
Keep the column bare so indexes work
A plain B-tree index on viewed_at can serve a range condition on viewed_at. It cannot serve a condition on an expression built from the column.
CREATE INDEX page_view_viewed_at_idx ON page_view (viewed_at);
-- Cannot use the index: the column is wrapped in a function or cast
SELECT count(*) FROM page_view
WHERE date_trunc('day', viewed_at) = TIMESTAMPTZ '2024-06-01 00:00:00+00';
SELECT count(*) FROM page_view
WHERE viewed_at::date = DATE '2024-06-01';
-- Can use the index: the column is compared directly
SELECT count(*) FROM page_view
WHERE viewed_at >= TIMESTAMPTZ '2024-06-01 00:00:00+00'
AND viewed_at < TIMESTAMPTZ '2024-06-02 00:00:00+00';The cast viewed_at::date also depends on the session TimeZone, so the same query can return different rows in different sessions. Rewriting it as a half-open range removes that dependence and makes the zone explicit in the bounds. On a small table the planner may choose a sequential scan anyway. Run EXPLAIN on a table with many rows to confirm that an index scan is possible.
Grouping versus filtering
Filtering and grouping are different jobs, and they use different tools:
- To filter, compare the bare column with computed bounds.
- To group by local day, apply the conversion to the column in the
SELECTandGROUP BYlist.
Combine them when you need both. Filter by a half-open range first, so the index narrows the rows. Then group the surviving rows:
SELECT date_trunc('day', viewed_at AT TIME ZONE 'America/New_York') AS local_day,
count(*) AS views
FROM page_view
WHERE viewed_at >= TIMESTAMPTZ '2024-06-01 00:00:00+00'
AND viewed_at < TIMESTAMPTZ '2024-07-01 00:00:00+00'
GROUP BY 1
ORDER BY 1;The grouping expression returns a plain timestamp in New York wall-clock time. Note that the filter range is a UTC month while the groups are New York days. The first and last groups can therefore be partial days. If you want whole New York days, build the bounds in New York time as shown earlier.
Overlap tests
Half-open ranges give a short, correct test for whether two periods overlap. Period A overlaps period B when each starts before the other ends:
-- Does the booking overlap the window [window_start, window_end)?
-- booking_start < window_end AND window_start < booking_end
SELECT *
FROM (VALUES
(1, TIMESTAMPTZ '2024-06-01 09:00:00+00', TIMESTAMPTZ '2024-06-01 10:00:00+00'),
(2, TIMESTAMPTZ '2024-06-01 10:00:00+00', TIMESTAMPTZ '2024-06-01 11:00:00+00')
) AS booking(id, booking_start, booking_end)
WHERE booking_start < TIMESTAMPTZ '2024-06-01 10:00:00+00'
AND TIMESTAMPTZ '2024-06-01 09:30:00+00' < booking_end;
-- Only id 1 is returned. Booking 2 starts exactly at the window end, so it does not overlap.Because both ends are exclusive on the right, a booking that ends at 10:00 and one that starts at 10:00 do not collide. With inclusive ends they would, and you would have to subtract a microsecond to avoid it.
Range types use the same convention
PostgreSQL has built-in range types for time: tsrange for timestamp and tstzrange for timestamptz. When you build one without a bounds argument, it is half-open: [). Operators such as @> (contains), && (overlaps), and -|- (adjacent) respect that.
SELECT tstzrange('2024-06-01 00:00:00+00', '2024-07-01 00:00:00+00')
@> TIMESTAMPTZ '2024-06-30 23:59:59.999999+00' AS contains_last_instant,
tstzrange('2024-06-01 00:00:00+00', '2024-07-01 00:00:00+00')
@> TIMESTAMPTZ '2024-07-01 00:00:00+00' AS contains_end,
tstzrange('2024-06-01 00:00:00+00', '2024-07-01 00:00:00+00')
-|- tstzrange('2024-07-01 00:00:00+00', '2024-08-01 00:00:00+00') AS adjacent,
tstzrange('2024-06-01 00:00:00+00', '2024-07-01 00:00:00+00')
&& tstzrange('2024-07-01 00:00:00+00', '2024-08-01 00:00:00+00') AS overlaps;
-- contains_last_instant: t
-- contains_end: f
-- adjacent: t
-- overlaps: fA later chapter covers ranges in more detail, including exclusion constraints that stop overlapping bookings. For now, note that the half-open pattern in your plain WHERE clauses and the range-type semantics are the same idea.
Dates compared with timestamps
A date column has no time of day, but the same rule applies to it. To select June, write d >= DATE '2024-06-01' AND d < DATE '2024-07-01'.
Be careful when you compare a date with a timestamptz. PostgreSQL converts the date to midnight in the session TimeZone, so viewed_at < DATE '2024-07-01' means "before July 1 at midnight in this session's zone". That is correct only if the session zone is the one you intend.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| `BETWEEN` with a `23:59:59` end | Rows with fractional seconds are missing | Use `>= start AND < next_start` |
| `BETWEEN` with next period's midnight | Boundary rows counted twice | Use `<` on the end bound |
| `end = start + interval '24 hours'` for a local day | Day is off by an hour on DST change days | Add `interval '1 day'` to a plain `timestamp`, then convert with `AT TIME ZONE` |
| `col::date = ...` or `date_trunc(..., col) = ...` in `WHERE` | No index scan, and results depend on session zone | Compare the bare column to computed bounds |
| Unqualified literal bounds | Different results per session | Add an offset, or set `TimeZone` deliberately |
Exercises
Exercise
A report counts orders for "June" with WHERE created_at BETWEEN '2024-06-01' AND '2024-06-30 23:59:59'. Give two different ways this query returns wrong results, and write the corrected condition.
Show answer
It drops any order created after 23:59:59 on June 30, such as 23:59:59.5, because the upper bound has no fractional seconds. It also depends on the session TimeZone, because the literals have no offset. The corrected form is WHERE created_at >= '2024-06-01 00:00:00+00' AND created_at < '2024-07-01 00:00:00+00', or equivalent bounds in the intended zone.
Exercise
Write the half-open filter for all rows that fall on 2024-11-03 in the America/New_York zone, where clocks go back at 02:00. Without running it, say how long the range is.
Show answer
WHERE ts >= TIMESTAMP '2024-11-03 00:00' AT TIME ZONE 'America/New_York' AND ts < TIMESTAMP '2024-11-04 00:00' AT TIME ZONE 'America/New_York'. The range is 25 hours long, because the 01:00 hour occurs twice on the fall-back day. Midnight on Nov 3 is EDT (UTC-4) and midnight on Nov 4 is EST (UTC-5).
Exercise
Why can WHERE viewed_at::date = DATE '2024-06-01' return different rows in two sessions, and how do you rewrite it so it can use a B-tree index on viewed_at?
Show answer
Casting a timestamptz to date uses the session TimeZone, so the same instant can fall on different dates in different zones. The cast also wraps the column, so a plain index on viewed_at cannot be used. Rewrite it as viewed_at >= TIMESTAMPTZ '2024-06-01 00:00:00+00' AND viewed_at < TIMESTAMPTZ '2024-06-02 00:00:00+00', or use bounds in the zone you intend.