date_bin Buckets Fixed Width Intervals
Bucket timestamps into fixed-width strides with date_bin anchored at an origin, where date_trunc can only align to calendar units.
Code
-- date_trunc 按日历单位对齐(整点/整日/整月);
-- date_bin(PG 14+)按固定宽度从 origin 起算分桶,宽度不必是日历边界
WITH events (ts, kind) AS (
VALUES (TIMESTAMPTZ '2026-11-15 09:07:00+00', 'click'),
(TIMESTAMPTZ '2026-11-15 09:14:30+00', 'click'),
(TIMESTAMPTZ '2026-11-15 09:22:10+00', 'view'),
(TIMESTAMPTZ '2026-11-15 09:29:59+00', 'click')
)
SELECT
date_bin(INTERVAL '15 minutes', ts, TIMESTAMPTZ '2026-11-15 09:00:00+00') AS bin_bucket,
date_trunc('hour', ts) AS calendar_hour,
count(*) FILTER (WHERE kind = 'click') AS clicks
FROM events
GROUP BY 1, 2
ORDER BY 1;
-- 09:07 与 09:14 落进第一个 15 分钟桶,09:22 与 09:29 落进第二个:
-- 同一归属在 date_trunc('hour') 下会被并进同一个整点桶Calendar alignment versus fixed strides
date_trunc only aligns to calendar units (hour, day, month). date_bin, available since PG 14, buckets by a fixed width measured from an origin: date_bin(INTERVAL ‘15 minutes’, ts, TIMESTAMPTZ ‘2026-11-15 09:00:00+00’) builds strides starting at 09:00 whether or not that is a clock boundary.
What the demo shows
Four events between 09:07 and 09:29:59 split into two 15-minute bins: the 09:07 and 09:14 clicks land in the first bin, the 09:22 view and 09:29:59 click in the second, and count(*) FILTER (WHERE kind = ‘click’) tallies clicks per bin alongside the calendar hour for contrast.
Where the difference matters
The same four events collapse into a single date_trunc(‘hour’) bucket; any metric that needs “first quarter-hour after 09:00” rather than “the 09:00 hour” must use date_bin.
Interactive Tools for This Topic
FAQ
- What does the origin argument in date_bin control?
- It sets the phase of the strides: bucket boundaries are origin + n × width, so the same 15-minute width shifts its edges when the origin changes.
- Why not use date_trunc for 15-minute buckets?
- date_trunc only aligns to calendar units; a 15-minute stride anchored at 09:00 is not a calendar unit, so date_bin is required.
Report a problem with this exampleOpens a pre-filled issue on GitHub.