// SQL snippet

Weekly buckets ending Sunday

date_trunc uses Monday starts; adding a DOW offset gives you Sunday-ending weeks.

Main statement
PostgreSQL
Também cobre
MySQL

The task

Your reports label each Monday-to-Sunday week by the Sunday it ends on. date_trunc('week') groups the same weeks but labels each one with its Monday.

The snippet

Written for PostgreSQL. Versions for MySQL are under Variations.

PostgreSQL
SELECT CAST(order_date AS date)
         + (7 - EXTRACT(DOW FROM order_date)::int) % 7 AS week_ending_sunday,
       COUNT(*) AS orders,
       SUM(amount) AS revenue
FROM orders
GROUP BY 1
ORDER BY 1;

Como funciona

EXTRACT(DOW) gives 0 for Sunday through 6 for Saturday in PostgreSQL. Subtracting it from 7 computes how many days remain until the next Sunday, and the modulo keeps a Sunday itself on the same day instead of jumping a week. The cast to date comes first because PostgreSQL can add an integer to a date but not to a timestamp. Group by the shifted date and each bucket is exactly one Monday-to-Sunday week.

Variations

ISO weeks starting Monday

SELECT DATE_TRUNC('week', order_date)::date AS week_starting_monday,
       COUNT(*) AS orders
FROM orders
GROUP BY 1
ORDER BY 1;

MySQL: DAYOFWEEK shift

MySQL
SELECT DATE_ADD(CAST(order_date AS date),
                INTERVAL (8 - DAYOFWEEK(order_date)) % 7 DAY) AS week_ending_sunday,
       COUNT(*) AS orders
FROM orders
GROUP BY 1
ORDER BY 1;

Questions that come up

Why do engines disagree on the week start?

ISO weeks start Monday, but US convention starts Sunday and MySQL's WEEKDAY/DAYOFWEEK functions disagree with each other. Computing the offset explicitly, as this recipe does, makes the convention visible instead of hidden in a function.

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.