Summarising Data with GROUP BY · Lesson 23 of 64

SQL Grouping by Dates

What you will learn

  • How to turn a date into a period (year, month, weekday)
  • How to group and sort by that period
  • How to build a monthly report
  • Why a period with no rows does not appear

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. From a date to a period

A date such as 2026-03-15 has too much detail to group by: almost every row has a different one. Group by a period that several rows share. Lesson 1.7 gave two tools: STRFTIME and plain text cutting with SUBSTR:

SELECT STRFTIME('%Y', '2026-03-15') AS year, STRFTIME('%Y-%m', '2026-03-15') AS year_month, SUBSTR('2026-03-15', 1, 7) AS same_year_month;
year  year_month  same_year_month
----  ----------  ---------------
2026  2026-03     2026-03
(1 row)
SELECT STRFTIME('%Y', '2026-03-15') AS year, STRFTIME('%Y-%m', '2026-03-15') AS year_month, SUBSTR('2026-03-15', 1, 7) AS same_year_month;
year  year_month  same_year_month
----  ----------  ---------------
2026  2026-03     2026-03
(1 row)
SELECT STRFTIME('%Y', '2026-03-15') AS year, STRFTIME('%Y-%m', '2026-03-15') AS year_month, SUBSTR('2026-03-15', 1, 7) AS same_year_month;
year  year_month  same_year_month
----  ----------  ---------------
2026  2026-03     2026-03
(1 row)

STRFTIME('%Y-%m', date) gives 2026-03, which sorts in time order as text.

2. Group by year

Payments per year:

SELECT STRFTIME('%Y', paid_on) AS year, COUNT(*) AS payments, ROUND(SUM(amount), 2) AS total
FROM payments GROUP BY STRFTIME('%Y', paid_on) ORDER BY year;
year  payments      total
----  --------  ---------
2024       422   43472.38
2025       845   82844.28
2026      1028  107012.23
(3 rows)

Ledger rows per year:

SELECT STRFTIME('%Y', txn_date) AS year, COUNT(*) AS rows_found, SUM(amount_cents) AS total_cents
FROM transactions GROUP BY STRFTIME('%Y', txn_date) ORDER BY year;
year  rows_found  total_cents
----  ----------  -----------
2018          84      1661424
2019         180      4124708
2020         352      7548812
2021         543     11511751
2022         657     14088701
2023         996     21960768
2024        1293     26734471
2025        1567     31905383
2026        1743     33077712
(9 rows)

Submissions per year:

SELECT STRFTIME('%Y', submitted_on) AS year, COUNT(*) AS submissions
FROM submissions WHERE submitted_on IS NOT NULL GROUP BY STRFTIME('%Y', submitted_on) ORDER BY year;
year  submissions
----  -----------
2025         2855
2026         1024
(2 rows)

(The expression in GROUP BY repeats the one in the SELECT. In SQLite you may group by the alias instead; repeating the expression works in every database.)

3. A monthly report

Group by year and month together. Because YYYY-MM sorts as text, ORDER BY puts the months in time order:

SELECT STRFTIME('%Y-%m', paid_on) AS month, COUNT(*) AS payments, ROUND(SUM(amount), 2) AS total
FROM payments WHERE paid_on >= '2026-01-01' GROUP BY STRFTIME('%Y-%m', paid_on) ORDER BY month;
month    payments     total
-------  --------  --------
2026-01       115  12410.84
2026-02       113  10535.69
2026-03       132  12940.38
2026-04        83   8361.24
2026-05       101  11283.29
2026-06       124   13991.9
2026-07       172  18773.58
2026-08       131  12976.98
2026-09        53   5288.92
2026-10         4    449.41
(10 rows)
SELECT STRFTIME('%Y-%m', txn_date) AS month, COUNT(*) AS rows_found, SUM(amount_cents) AS total_cents
FROM transactions WHERE txn_date >= '2026-01-01' GROUP BY STRFTIME('%Y-%m', txn_date) ORDER BY month;
month    rows_found  total_cents
-------  ----------  -----------
2026-01         153      2935119
2026-02         153      2936771
2026-03         198      3718984
2026-04         167      3286380
2026-05         185      3350849
2026-06         205      4288625
2026-07         229      4275349
2026-08         230      4223106
2026-09         223      4062529
(9 rows)
SELECT STRFTIME('%Y-%m', submitted_on) AS month, COUNT(*) AS submissions
FROM submissions WHERE submitted_on >= '2025-09-01' GROUP BY STRFTIME('%Y-%m', submitted_on) ORDER BY month;
month    submissions
-------  -----------
2025-09          408
2025-10          422
2025-11          383
2026-02          199
2026-03          419
2026-04          361
2026-05           45
(7 rows)

Read the months from top to bottom and look for gaps and trends. This is the shape of most business reports.

4. Group by weekday

STRFTIME('%w', date) gives the weekday as a number: 0 is Sunday, 1 Monday and so on. A CASE (lesson 2.8) or a lookup can turn it into a name:

SELECT STRFTIME('%w', order_date) AS weekday_number, COUNT(*) AS orders
FROM orders GROUP BY STRFTIME('%w', order_date) ORDER BY weekday_number;
weekday_number  orders
--------------  ------
0                  380
1                  409
2                  352
3                  395
4                  363
5                  334
6                  367
(7 rows)
SELECT STRFTIME('%w', txn_date) AS weekday_number, COUNT(*) AS rows_found
FROM transactions GROUP BY STRFTIME('%w', txn_date) ORDER BY weekday_number;
weekday_number  rows_found
--------------  ----------
0                     1054
1                     1091
2                     1108
3                     1033
4                     1090
5                     1027
6                     1012
(7 rows)
SELECT STRFTIME('%w', class_date) AS weekday_number, status, COUNT(*) AS rows_found
FROM attendance GROUP BY STRFTIME('%w', class_date), status ORDER BY weekday_number, status LIMIT 8;
weekday_number  status   rows_found
--------------  -------  ----------
1               absent           84
1               late             83
1               present        1189
2               absent           79
2               late             58
2               present         991
3               absent          102
3               late             79
(8 rows)

5. A month with no rows does not appear

GROUP BY makes a group only for values that exist. If nothing happened in a month, that month is simply missing from the result, not shown as 0. A report that needs every month must build the list of months separately and join it (chapter 4 and the recursive queries of chapter 7). For now, look for gaps in the month numbers when you read a result.

Worked example: payments per quarter

A quarter is three months. There is no %q in STRFTIME, so you calculate it from the month number:

Step Expression
month as a number CAST(STRFTIME('%m', paid_on) AS INTEGER)
quarter (month - 1) / 3 + 1 with whole-number division
together (CAST(STRFTIME('%m', paid_on) AS INTEGER) - 1) / 3 + 1

Group by that expression and you have the quarters 1 to 4. Whole-number division (lesson 1.3) is what makes (month - 1) / 3 give 0, 1, 2 or 3. The table is made up.

Common mistakes

  • Grouping by the full date when you wanted a month.
  • Sorting by a month name, which is alphabetical. Sort by YYYY-MM.
  • Mixing years when you group by month number only (%m): January of every year lands in one group.
  • Expecting a month with no rows to show as 0.
  • Using 'now' in a report you want to repeat exactly.

Key takeaways

  • Group by a period (STRFTIME('%Y-%m', date)), not the full date.
  • YYYY-MM text sorts in time order, so ORDER BY it.
  • %w gives the weekday number (0 is Sunday).
  • Groups exist only where rows exist; gaps are not filled in.

Practice

1. Which expression gives the year and month of paid_on?

Show answer

STRFTIME('%Y-%m', paid_on)

2. Why group by YYYY-MM and not by the month number alone?

Show answer

The month number alone mixes the same month of different years into one group.

3. What does %w return for a Monday?

Show answer

1 (Sunday is 0).

4. Why does a month with no payments not appear in the result?

Show answer

GROUP BY only creates groups for values that exist in the rows.

5. How do you sort the months in time order?

Show answer

ORDER BY the YYYY-MM text; it sorts as text in time order.

6. Write the expression for the quarter of a month number m.

Show answer

(m - 1) / 3 + 1 (with whole-number division).