// SQL snippet

Count rows bucketed by time period

Pull the period key out of the date with EXTRACT, group on it, and count: row counts per day, month or quarter in one query.

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

The task

A per-month order census shows ingestion rhythm and dead months at once. It is the time-based cousin of the value histogram.

The snippet

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

PostgreSQL
SELECT EXTRACT(YEAR FROM order_date) AS order_year,
       EXTRACT(MONTH FROM order_date) AS order_month,
       COUNT(*) AS order_count
FROM orders
WHERE order_date IS NOT NULL
GROUP BY EXTRACT(YEAR FROM order_date), EXTRACT(MONTH FROM order_date)
ORDER BY order_year, order_month;

仕組み

EXTRACT pulls the year and month out of each date, and GROUP BY both produces one row per calendar month. Ordering by year then month reads like a timeline; gaps in the sequence are months with no rows at all (see the date-gap recipe for a calendar that fills them). The statement runs unchanged on MySQL and Oracle. SQL Server has no EXTRACT, so use YEAR() and MONTH() (second variant); on SQLite group by strftime('%Y-%m', order_date).

Variations

Custom business buckets with CASE (all five engines)

SELECT order_size, COUNT(*) AS order_count
FROM (
  SELECT CASE
           WHEN total < 50 THEN 'small'
           WHEN total < 200 THEN 'medium'
           ELSE 'large'
         END AS order_size
  FROM orders
  WHERE total IS NOT NULL
) sized
GROUP BY order_size
ORDER BY order_count DESC;

SQL Server: YEAR() and MONTH()

SQL Server
SELECT YEAR(order_date) AS order_year,
       MONTH(order_date) AS order_month,
       COUNT(*) AS order_count
FROM orders
WHERE order_date IS NOT NULL
GROUP BY YEAR(order_date), MONTH(order_date)
ORDER BY order_year, order_month;

Week buckets (PostgreSQL date_trunc)

PostgreSQL
SELECT date_trunc('week', order_date) AS week_start,
       COUNT(*) AS order_count
FROM orders
WHERE order_date IS NOT NULL
GROUP BY 1
ORDER BY 1;

Questions that come up

Why not GROUP BY DATE_TRUNC directly?

On PostgreSQL you can, and the result is a real date you can chart directly. Elsewhere the truncation function has a different name: TRUNC(order_date, 'MM') on Oracle, DATETRUNC(month, order_date) on SQL Server 2022+, date(order_date, 'start of month') on SQLite, and nothing built in on MySQL. Week buckets differ further: date_trunc('week') starts weeks on Monday, while SQL Server's DATETRUNC(week) follows the DATEFIRST setting, Sunday by default in US English.

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.