// SQL snippet

Bucket timestamps into 5-minute windows in SQL

Charts and rate alerts need events grouped into fixed windows. Epoch flooring makes the bucket boundary independent of any calendar rules.

Main statement
PostgreSQL
还支持
SQL Server MySQL

The task

Divide the epoch seconds by the window size, floor it, and multiply back: every timestamp lands on a 5-minute mark.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
SELECT
    to_timestamp(floor(extract(epoch from occurred_at) / 300) * 300) AS bucket_start,
    count(*) AS events
FROM page_views
GROUP BY 1
ORDER BY 1;

工作原理

extract(epoch) gives seconds since 1970 as a continuous number, so dividing by 300 and flooring snaps to the containing 5-minute window regardless of time zones, DST or month lengths. to_timestamp converts the bucket edge back to a timestamptz, which displays in the session time zone; if occurred_at is a plain timestamp, append AT TIME ZONE 'UTC' to get a plain timestamp back. Change 300 to 60, 900 or 3600 for other window sizes. PostgreSQL 14+ can write the same bucket as date_bin('5 minutes', occurred_at, TIMESTAMP '2000-01-01').

Variations

SQL Server

SQL Server
SELECT
    DATEADD(MINUTE, (DATEDIFF(MINUTE, '2000-01-01', occurred_at) / 5) * 5, '2000-01-01') AS bucket_start,
    COUNT(*) AS events
FROM page_views
GROUP BY DATEADD(MINUTE, (DATEDIFF(MINUTE, '2000-01-01', occurred_at) / 5) * 5, '2000-01-01')
ORDER BY bucket_start;

MySQL

MySQL
SELECT
    FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(occurred_at) / 300) * 300) AS bucket_start,
    COUNT(*) AS events
FROM page_views
GROUP BY bucket_start;

Questions that come up

Why floor epoch seconds instead of date_trunc?

date_trunc only snaps to whole units such as minutes, hours and days. Epoch flooring works for any window size, on any PostgreSQL version, and stays correct across DST because epoch seconds are zone-free. On PostgreSQL 14+ date_bin does the same job, and SQL Server 2022+ has DATE_BUCKET(minute, 5, occurred_at).

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.