Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL date_bin: Bucket Timestamps by Step

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL's date_bin function snaps a timestamp down to the start of the nearest fixed-size interval (a "bin") counted from a chosen origin. It takes three arguments: date_bin(stride, source, origin). It returns the lower edge of the bucket that contains source. That is exactly what you want when you need to group events into regular 5-minute, 15-minute, one-hour or one-day windows, produce time-series rollups, or align sampling intervals. It is available in PostgreSQL 14 and later; on older versions the function does not exist and you have to fall back on date_trunc or arithmetic on the timestamp. Nothing apart from a working PostgreSQL 14+ connection is genuinely required, though a table with timestamp data makes it easier to follow along.

What You'll Need

  • A PostgreSQL 14 or newer server, and a client such as psql, pgAdmin or any SQL tool. Run SELECT version(); to confirm the version.
  • A timestamp column, ideally of type timestamptz, and general comfort with SELECT statements, GROUP BY and interval literals.
  • Awareness of your session time zone (SHOW timezone;), because bucketing timestamptz values near a DST change can behave in ways that surprise you.

Step-by-Step

  1. Understand the signature. date_bin(stride interval, source timestamp, origin timestamp) returns a timestamp (or timestamptz) that is the start of the bin containing source. The stride is the bin width, the source is the value being placed, and the origin is the anchor point that all bins are counted from.
  2. Run a minimal query first. In psql, type:
    SELECT date_bin('15 minutes', TIMESTAMP '2026-03-02 10:37:00', TIMESTAMP '2000-01-01');
    You should get 2026-03-02 10:30:00. The bin starts at 10:30 and covers 10:30 up to (but not including) 10:45.
  3. Pick the origin deliberately. If you use midnight ('2000-01-01') as the origin, bins line up on clock quarters; if you use '2000-01-01 00:07:00', your bins are offset by seven minutes. The origin only changes alignment, not the bucket width.
  4. Bucket a table of events. With a table called readings(ts timestamptz, value numeric), group with:
    SELECT date_bin('1 hour', ts, TIMESTAMPTZ '2000-01-01') AS bucket, AVG(value) AS avg_value, COUNT(*) FROM readings GROUP BY bucket ORDER BY bucket;
    This gives hourly averages for every hour that contains data.
  5. Fill gaps if you need continuous output. date_bin only returns bins that actually contain rows. To get every interval, generate the series with generate_series(start, stop, '1 hour') and left-join your aggregate onto it. The generated timestamps align with date_bin only if you use the same origin.
  6. Bucket by day with care. Use date_bin('1 day', ts, '2000-01-01') only when you really want a fixed 24-hour window. If you need calendar days that reset at local midnight, date_trunc('day', ts) is usually the more correct tool.
  7. Check your time zone results. For timestamptz inputs, the bin is computed in absolute time, so one-hour bins across a DST switch simply continue; a fixed 24-hour stride will not match local calendar days. If local-day buckets matter, consider date_bin('1 day', ts AT TIME ZONE 'UTC', ...) or date_trunc.
  8. Validate the output. Recompute the bin for one known row by hand and compare. Check that the highest bin start plus one stride is greater than or equal to your newest event, and that counts in the bins sum to your total row count.
  9. Encountering a version error. If you see function date_bin(unknown, timestamp, timestamp) does not exist, the server is older than 14. Use date_trunc or to_timestamp(floor(extract(epoch FROM ts)/900)*900) for 15-minute bins as a substitute until you can upgrade.

Common Mistakes

The most frequent error is passing a stride that is not an interval, such as the string '15' or an integer. Always wrap the value: INTERVAL '15 minutes' or the literal '15 min' cast to interval. Another classic: using an origin you do not control and then wondering why buckets fall on odd offsets. Origin is your design decision, so set it explicitly and reuse it consistently across queries.

Mix-and-match types cause errors too. date_bin needs all three arguments compatible: timestamptz source with a timestamp origin, or the reverse, can throw a type mismatch. Use explicit casts. A common logic mistake is treating bin labels as the bin's end rather than its start, which off-by-one-shifts all time labels. Also, a zero or negative stride raises an error; the stride must be greater than zero. Finally, do not confuse date_bin with date_trunc: date_trunc aligns to calendars and local time, date_bin aligns to a fixed width from your origin, with no notion of a calendar month.

Tips

  • Wrap your binning expression in a subquery or CTE and reuse the label, rather than repeating the same expression in SELECT and GROUP BY. PostgreSQL also accepts the output alias in GROUP BY in many cases, but a subquery is clearer.
  • Create an index on the timestamp column; date_bin itself is not indexable, so filter by raw timestamp ranges before bucketing where possible.
  • Choose bin widths that divide evenly, such as 5, 15, 30 or 60 minutes, so origins stay predictable.
  • Store the origin as a named constant in your query or application so every report uses identical alignment.
  • For sparse data, filter the joined result with a predicate if you want to drop empty bins rather than keep them.

Troubleshooting

If the function does not exist, confirm the server version as described above; a client version does not help, only the server matters. If you get cannot cast type integer to interval, multiply the stride properly: make_interval(mins => 15) or ('15 minutes')::interval. If all bins appear shifted, print one bin start and compare it with a known value: the origin is almost certainly not what you think. If bins vanish at random, check for NULL timestamps; date_bin returns NULL for a NULL source, and those rows are simply excluded from grouping. If results differ between two clients, run SHOW timezone; in each; a different session time zone changes how timestamptz values display and can change behavior across DST boundaries. If the query is slow on a large table, add a range filter and an index on the timestamp column, then bucket the filtered subset. If you are migrating from a manual floor/epoch approach, verify a small sample against the old formula before switching dashboards over, since an origin that does not match the old alignment will silently shift every result by up to one stride.

Frequently Asked Questions

Does date_bin exist in all PostgreSQL versions?

No. It was added in PostgreSQL 14. Older servers need date_trunc or epoch arithmetic as substitutes.

What is the difference between date_bin and date_trunc?

date_bin creates fixed-width windows starting from an origin you choose, so any width works. date_trunc truncates to calendar boundaries (hour, day, week, month) and respects local time for timestamptz.

Can I use date_bin to group by arbitrary seconds?

Yes. The stride accepts any interval, for example INTERVAL '30 seconds' or INTERVAL '7 minutes'.

What happens with NULL timestamps?

The function returns NULL, so those rows fall outside any group when you group by the bin expression.

How do I include empty buckets?

Generate the alignment with generate_series using the same origin and left-join your aggregation onto it. date_bin alone never returns empty bins.

Does the origin argument change bucket width?

No. Width is set only by the stride. The origin changes where the boundaries fall on the timeline.