// SQL snippet

Group rows into hourly buckets

DATE_TRUNC rounds every timestamp down to the hour; GROUP BY the truncated value.

Main statement
PostgreSQL
Também cobre
SQL Server MySQL SQLite

The task

You want orders per hour of the day to staff your support desk properly.

The snippet

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

PostgreSQL
SELECT DATE_TRUNC('hour', order_date) AS hour_bucket,
       COUNT(*) AS orders,
       SUM(amount) AS revenue
FROM orders
GROUP BY 1
ORDER BY 1;

Como funciona

DATE_TRUNC('hour', ...) zeroes out the minutes and seconds, so every timestamp in an hour maps to the same value and GROUP BY counts it once. GROUP BY 1 refers to the first output column, avoiding a repeated expression. Each engine has its own truncation function: MySQL uses DATE_FORMAT, SQL Server 2022+ DATETRUNC(hour, ...) (older versions the DATEADD/DATEDIFF trick), SQLite strftime, Oracle TRUNC(order_date, 'HH24').

Variations

MySQL: DATE_FORMAT

MySQL
SELECT DATE_FORMAT(order_date, '%Y-%m-%d %H:00:00') AS hour_bucket,
       COUNT(*) AS orders
FROM orders
GROUP BY 1
ORDER BY 1;

SQL Server: DATEDIFF bucket trick (any version)

SQL Server
SELECT DATEADD(hour, DATEDIFF(hour, 0, order_date), 0) AS hour_bucket,
       COUNT(*) AS orders
FROM orders
GROUP BY DATEADD(hour, DATEDIFF(hour, 0, order_date), 0)
ORDER BY hour_bucket;

SQLite: strftime

SQLite
SELECT strftime('%Y-%m-%d %H:00:00', order_date) AS hour_bucket,
       COUNT(*) AS orders
FROM orders
GROUP BY 1
ORDER BY 1;

Questions that come up

Can I bucket by time-of-day across all days?

Yes: group by the hour part only, such as EXTRACT(hour FROM order_date) in PostgreSQL or DATEPART(hour, order_date) in SQL Server, to get one row per hour of the day summed across every date.

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.