Kodewick
Start learning →
By month and by week2 / 12

By month and by week

Lesson 2 of 12 · Part 1 · Know your data · about 20 minutes

By month: GROUP BY DATE_FORMAT(order_date, '%Y-%m'). Average order value = sales ÷ orders. Months with no orders don't appear in the result. By week: DATE_SUB(d, INTERVAL WEEKDAY(d) DAY) gives the Monday of that week.

The health check is done, and here comes the boss's first question: "How did each month go this year?" This is the most common report there is: you take the orders, one by one, and gather them into one row of numbers per month.

Totals by month

In this step you group the orders by month. DATE_FORMAT(order_date, '%Y-%m') turns 2025-03-14 into 2025-03, so every order in the same month gets the same value, and you group by it. Remember to count only paid orders:

main.sql
1SELECT DATE_FORMAT(order_date, '%Y-%m') AS month,2    COUNT(*) AS orders,3    SUM(amount) AS sales4FROM orders5WHERE status = 'paid'6GROUP BY month7ORDER BY month;
Output
monthorderssales
2025-01136
2025-037366
2025-042126
2025-0511743
2025-065310
2025-0713820
2025-0811626
2025-0916977
2025-1012789
2025-11211042
2025-1216588
11 rows

November is the busiest month: 21 orders and 1042 in sales. That's the big November sales, like Singles' Day and Black Friday.

orders
order_dateamount
2025-11-0236
2025-11-0525
……
2025-12-0424
……
GROUP BY DATE_FORMAT(order_date, '%Y-%m')
result
monthorderssales
2025-11211042
2025-1216588
Each order first becomes its month, then the orders are grouped by month and added up

Other databases: DATE_FORMAT is how MySQL does it. In PostgreSQL you write TO_CHAR(order_date, 'YYYY-MM') or DATE_TRUNC('month', order_date), and in SQL Server FORMAT(order_date, 'yyyy-MM').

Choose one

Why group by DATE_FORMAT(order_date, '%Y-%m') instead of simply MONTH(order_date)?

A missing month

In this step you meet a trap that's easy to miss. Count the rows of the monthly result: January, March, April… 11 rows in all. February is gone.

February has no paid orders at all. GROUP BY can only group rows that exist, so a month with no orders simply doesn't appear. It doesn't show up as 0 either. On a line chart, January joins straight to March, and nobody notices February was empty.

main.sql
1SELECT COUNT(DISTINCT DATE_FORMAT(order_date, '%Y-%m')) AS months2FROM orders3WHERE status = 'paid';
Output
months
11
1 row

To fill February in as 0, you first need a table of all 12 months, then LEFT JOIN the orders to it. Lesson 10 shows how to make that table with WITH RECURSIVE. For now, just remember: when you group by time, check that no time periods are missing.

Fill inTap one to fill a blank; tap a blank to take it back

From January 1 to January 7, the shop had orders on only 3 of the days. If you group by day and count orders, how many rows does the result have?

1SELECT order_date, COUNT(*) AS n2FROM orders3WHERE order_date BETWEEN '2025-01-01' AND '2025-01-07'4GROUP BY order_date;5-- the result has  rows

Average order value and buyers

In this step you work out two numbers bosses often ask for. Average order value is how much one order is worth on average: sales ÷ orders, which is just AVG(amount). Buyers is how many people bought something that month: someone who bought twice still counts once, so use COUNT(DISTINCT user_id).

main.sql
1SELECT DATE_FORMAT(order_date, '%Y-%m') AS month,2    COUNT(*) AS orders,3    SUM(amount) AS sales,4    ROUND(AVG(amount), 1) AS avg_order5FROM orders6WHERE status = 'paid'7GROUP BY month8ORDER BY month;
Output
monthorderssalesavg_order
2025-0113636.0
2025-03736652.3
2025-04212663.0
2025-051174367.5
2025-06531062.0
2025-071382063.1
2025-081162656.9
2025-091697761.1
2025-101278965.8
2025-1121104249.6
2025-121658836.8
11 rows

November has the most orders, yet the average order value fell from 65.8 in October to 49.6, and in December it's even lower, just 36.8. More orders, but smaller ones: during the sales, many people probably bought only small, cheap things. You'd never see this from sales alone.

Exercise 1

Buyers in the last three months

For October, November and December, find the number of paid orders and the number of buyers each month. Three columns: month (written like 2025-10), orders and buyers, sorted by month.

It should print
monthordersbuyers
2025-101211
2025-112118
2025-121615
3 rows
exercise1.sql
1SELECT DATE_FORMAT(order_date, '%Y-%m') AS month2FROM orders3WHERE status = 'paid'4    AND order_date >= '2025-10-01'5GROUP BY month6ORDER BY month;
Output
Press Run or Ctrl+Enter

Which day of the week sells most

In this step you look from another angle: group by day of the week instead of by month. DAYNAME gives the English name of the day, and WEEKDAY gives a number: Monday is 0 and Sunday is 6.

main.sql
1SELECT DAYNAME(order_date) AS day, COUNT(*) AS orders2FROM orders3WHERE status = 'paid'4GROUP BY day, WEEKDAY(order_date)5ORDER BY WEEKDAY(order_date);
Output
dayorders
Monday16
Tuesday16
Wednesday6
Thursday12
Friday24
Saturday22
Sunday19
7 rows

Friday and Saturday have the most orders, and Wednesday has only 6. If you want to run a promotion, just before the weekend is a good time.

Why sort by WEEKDAY and not by day? day is text, so it sorts alphabetically: Friday, Monday, Saturday… and the days of the week are all jumbled. Sorting by the WEEKDAY number gives Monday to Sunday.

Choose oneA wrong guess is fine

If you change the sort to ORDER BY day, which day is in the first row?

1SELECT DAYNAME(order_date) AS day, COUNT(*) AS orders2FROM orders3WHERE status = 'paid'4GROUP BY day5ORDER BY day;

How long until the first order

In this step you work out how many days lie between two dates. First, use WITH to find the day of each person's first paid order. Then compare it with their sign-up date. DATEDIFF(later, earlier) gives the number of days between them:

main.sql
1WITH first_orders AS (2    SELECT user_id, MIN(order_date) AS first_order3    FROM orders4    WHERE status = 'paid'5    GROUP BY user_id6)7SELECT u.name, u.signup_date, f.first_order,8    DATEDIFF(f.first_order, u.signup_date) AS days9FROM users AS u10JOIN first_orders AS f ON f.user_id = u.id11ORDER BY days DESC, u.id12LIMIT 5;
Output
namesignup_datefirst_orderdays
Carla2025-01-122025-05-19127
Vera2025-06-232025-10-09108
Paula2025-04-032025-07-14102
Gabi2025-02-042025-05-0388
Emil2025-08-172025-11-1085
5 rows

Carla signed up in January but didn't order until May: 127 days later. She's the kind of user who signed up but wasn't won over. A discount coupon early on might have got her to order much sooner.

Exercise 2

People who ordered within a week

Find the users whose first paid order came within 7 days of signing up (day 7 included). Two columns: name and days, sorted by days from smallest to largest, with ties sorted by user id.

It should print
namedays
Will1
Jade2
Tomas3
Hana3
Olga5
Mel7
6 rows
exercise2.sql
1WITH first_orders AS (2    SELECT user_id, MIN(order_date) AS first_order3    FROM orders4    WHERE status = 'paid'5    GROUP BY user_id6)7SELECT u.name8FROM users AS u9JOIN first_orders AS f ON f.user_id = u.id;
Output
Press Run or Ctrl+Enter

By week

In this step you group by week. In a weekly report, "the week of December 1" is easier to read than "week 49". The trick is to move each date back to the Monday of its week: WEEKDAY tells you which day of the week it is (Monday is 0), and going back that many days lands on Monday.

main.sql
1SELECT DATE_SUB(order_date, INTERVAL WEEKDAY(order_date) DAY) AS week_start,2    COUNT(*) AS orders,3    SUM(amount) AS sales4FROM orders5WHERE status = 'paid'6    AND order_date >= '2025-12-01'7GROUP BY week_start8ORDER BY week_start;
Output
week_startorderssales
2025-12-01260
2025-12-084126
2025-12-158288
2025-12-222114
4 rows

The week of December 15 is the busiest, with 8 orders. All 7 days of a week move back to the same Monday, so they land in the same group.

Tip: MySQL also has WEEK() and YEARWEEK(), but whether a week starts on Sunday or Monday, and which year the first days of January belong to, depends on the second argument, and it's easy to get wrong. "Move back to Monday" is clear at a glance.

Put in orderDrag, or use the arrows

Put these lines in order to make a query that runs: count the paid orders in each week of November, with each week shown as its Monday.

  1. FROM orders
  2. GROUP BY week_start
  3. ORDER BY week_start;
  4. SELECT DATE_SUB(order_date, INTERVAL WEEKDAY(order_date) DAY) AS week_start, COUNT(*) AS orders
  5. WHERE status = 'paid' AND order_date BETWEEN '2025-11-01' AND '2025-11-30'
Should print
week_start | orders
2025-10-27 | 1
2025-11-03 | 7
2025-11-10 | 7
2025-11-17 | 1
2025-11-24 | 5

What you learned

  • To group by month, use DATE_FORMAT(d, '%Y-%m'). It includes the year, so different years never get mixed.
  • Months or days with no data don't appear in a GROUP BY result. Check for yourself that no periods are missing.
  • Average order value = sales ÷ orders, which is AVG(amount). Count buyers with COUNT(DISTINCT user_id). Sales alone hide changes like "more orders, but smaller ones".
  • To group by day of the week, use DAYNAME, and sort by WEEKDAY.
  • DATEDIFF(later, earlier) gives the days between two dates. Find each person's first order with WITH first, then compare it with their sign-up date.
  • By week: DATE_SUB(d, INTERVAL WEEKDAY(d) DAY) moves a date back to the Monday of its week.
Finished lesson 2?Lesson 2 of 12 · progress stays in this browser
Next · lesson 3 · 20 minBucketsUse CASE to sort orders into small, medium and large and customers into tiers A, B and C; turn rows into columns with SUM(CASE …) to build a pivot table by quarter; count by condition to get each city's cancel rate.Next lesson →
The button marks this lesson done and opens the next.
Practise what this lesson taught#021GROUP BY MONTH()Sales per monthStarter#033SUM(action = …)Actions per dayBasicAll 50 SQL problems →