// SQL snippet

Round timestamps to the nearest minute or hour in SQL

Logging pipelines normalize timestamps: truncate for bucket keys, round-to-nearest when the exact second does not matter.

Main statement
PostgreSQL
次もカバーします
SQL Server MySQL

The task

date_trunc floors to a unit; date_bin (PostgreSQL 14+) floors to any interval, such as 15 minutes. Rounding to the nearest unit is a floor after adding half a unit.

The snippet

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

PostgreSQL
SELECT
    date_trunc('hour', occurred_at) AS hour_start,
    date_bin(interval '15 minutes', occurred_at, TIMESTAMP '2000-01-01') AS quarter_hour,
    date_trunc('minute', occurred_at + interval '30 seconds') AS rounded_minute,
    date_trunc('hour', occurred_at + interval '30 minutes') AS rounded_hour
FROM events;

仕組み

date_trunc('hour') always floors: 10:59:31 becomes 10:00. date_bin floors to any stride measured from the origin in its third argument, which is required. Adding half the unit before truncating turns the floor into round-to-nearest, so 10:59:31 rounds to 11:00 both for the minute and for the hour. On a timestamptz column date_trunc works in the session time zone.

Variations

SQL Server

SQL Server
SELECT
    DATEADD(MINUTE, DATEDIFF(MINUTE, '2000-01-01', occurred_at), '2000-01-01') AS minute_trunc,
    DATEADD(HOUR, DATEDIFF(HOUR, '2000-01-01', occurred_at), '2000-01-01') AS hour_trunc,
    DATEADD(MINUTE, DATEDIFF(MINUTE, '2000-01-01', DATEADD(SECOND, 30, occurred_at)), '2000-01-01') AS rounded_minute
FROM events;

MySQL

MySQL
SELECT
    DATE_FORMAT(occurred_at, '%Y-%m-%d %H:00:00') AS hour_trunc,
    DATE_FORMAT(occurred_at, '%Y-%m-%d %H:%i:00') AS minute_trunc
FROM events;

Questions that come up

Is there a difference between truncating and rounding?

Yes and it matters: truncation puts 10:59:59 in the 10:00 bucket, rounding puts it in 11:00. Charts usually want truncation; de-duplication and approximate matching often want rounding. Pick deliberately, not by whichever function you found first.

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.