Forgly

SQL to group by week

Summarize rows per week — and handle the week-numbering quirks each dialect has.

PostgreSQL
SELECT DATE_TRUNC('week', created_at) AS week,
       COUNT(*) AS orders
FROM orders
GROUP BY DATE_TRUNC('week', created_at)
ORDER BY week;

DATE_TRUNC('week', ...) snaps each timestamp back to the Monday that starts its ISO week, giving one clean date per week.

MySQL
SELECT YEARWEEK(created_at, 3) AS week,
       COUNT(*) AS orders
FROM orders
GROUP BY YEARWEEK(created_at, 3)
ORDER BY week;

Mode 3 uses ISO 8601 weeks (Monday start) and folds the year in, so week 1 of 2024 never merges with week 1 of 2025.

SQL Server
SELECT YEAR(created_at) AS year,
       DATEPART(ISO_WEEK, created_at) AS iso_week,
       COUNT(*) AS orders
FROM orders
GROUP BY YEAR(created_at), DATEPART(ISO_WEEK, created_at)
ORDER BY year, iso_week;

DATEPART(ISO_WEEK, ...) gives ISO week numbers; pairing with YEAR() keeps different years apart (see the tip for the early-January edge case).

SQLite
SELECT strftime('%Y-%W', created_at) AS week,
       COUNT(*) AS orders
FROM orders
GROUP BY strftime('%Y-%W', created_at)
ORDER BY week;

%W counts weeks from the first Monday of the year (00-53).

How to group records by week

Grouping by week buckets rows into 7-day periods. The catch is that engines disagree on when a week starts and how weeks are numbered, so use an explicit, ISO-friendly approach.

How it works

  • A week bucket is just the timestamp reduced to a single value that is identical for all 7 days of that week.
  • Postgres DATE_TRUNC keeps a real date (the week's Monday); MySQL/SQLite use a year-week label; SQL Server groups by year plus ISO week number.
  • Always include the year (or use a function that does), or the same week number from different years collapses together.

Tip

Pick ISO weeks (Monday start) and stick to it. Note the boundary case: ISO can place the first days of January in the last week of the previous year — that is correct ISO behavior, not a bug.

Related SQL queries

Frequently asked questions

How do I group records by week in SQL?

Grouping by week buckets rows into 7-day periods. The catch is that engines disagree on when a week starts and how weeks are numbered, so use an explicit, ISO-friendly approach. A week bucket is just the timestamp reduced to a single value that is identical for all 7 days of that week. Postgres DATE_TRUNC keeps a real date (the week's Monday); MySQL/SQLite use a year-week label; SQL Server groups by year plus ISO week number. Always include the year (or use a function that does), or the same week number from different years collapses together.

Does this work in PostgreSQL, MySQL, SQL Server, and SQLite?

Yes — this page lists the query for each dialect, since the syntax can differ between database engines.

Can I generate this query for my own tables?

Yes. Describe what you want in plain English with Forgly's free AI SQL Generator and it writes the query for your dialect.