Scenario: Brightlane's operations team monitors weekly order volume to detect demand fluctuations.
Task: Write a query to return each calendar week and the number of orders placed in that week.
Assumptions:
- The
orderstable holds one row per placed order, with the placement timestamp stored inordered_at. - A calendar week is identified by its starting Monday and covers every order placed within that week.
Output:
- One row per calendar week present in the data.
- Columns in this order:
week_start(the first day of the calendar week, a Monday),order_count.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
DATE_TRUNC('week', ordered_at)::date AS week_start,
COUNT(*) AS order_count
FROM
orders
GROUP BY
DATE_TRUNC('week', ordered_at) The shape
date_trunc('week', ordered_at) snaps every order timestamp back to the Monday that opens its week, so every order placed Monday through Sunday inside the same week shares a single grouping key. The aggregate runs once per week and returns one row per calendar week with the count of orders placed within it.
Clause by clause
SELECT date_trunc('week', ordered_at)::date AS week_start, COUNT(*) AS order_countreturns one row per week. The::datecast turns the truncated Monday-at-midnight timestamp into a plain date for display.COUNT(*)counts the orders that fall inside that week.FROM ordersreads every placed order. There is noWHERE; the operations team wants every week in scope.GROUP BY date_trunc('week', ordered_at)repeats the same truncation as the grouping key. An order placed Tuesday and an order placed Sunday of the same ISO week both truncate to that week's Monday and end up in the same group.
The trap
PostgreSQL's date_trunc('week', ...) always anchors weeks on Monday, following the ISO 8601 convention. If the reporting context expects Sunday-starting weeks, the truncation will pull Sunday orders into the previous week's bucket instead of the next one, and the counts will not match a Sunday-anchored report. There is no parameter on date_trunc to change this. When ISO weeks are the right reporting convention, the function works as shown; when Sunday-anchored weeks are required, the date has to be shifted by a day before and after the truncation.
You practiced truncating timestamps to the ISO week start so orders within the same Monday-anchored week collapse into one row.