Kodewick
Start learning →
Compare with before: month over month6 / 12

Compare with before: month over month

Lesson 6 of 12 · Part 2 · Window functions at work · about 20 minutes

Month over month: sales - LAG(sales) OVER (ORDER BY month), and divide by LAG(sales) for the growth rate. The previous row isn't always last month, so check. Year over year: LAG(sales, 12). Gaps per person: LAG(order_date) OVER (PARTITION BY user_id ORDER BY order_date). The row where LEAD is NULL is the last one.

There are two questions the boss loves to ask about a report: "Is it up or down from last month?" and "Do our old customers come back?" Both mean comparing a row with the row before it. You learned LAG and LEAD in the beginner course. This lesson uses them for monthly reports and customer analysis.

Month over month

In this step you work out the month-over-month change: this month compared with last month. LAG(sales) takes sales from the previous row. Subtract, and you get how much it went up or down. Divide that by last month's number, and you get the growth rate:

main.sql
1WITH monthly AS (2    SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(amount) AS sales3    FROM orders4    WHERE status = 'paid'5    GROUP BY month6)7SELECT month, sales,8    LAG(sales) OVER (ORDER BY month) AS prev,9    sales - LAG(sales) OVER (ORDER BY month) AS diff,10    ROUND(100 * (sales - LAG(sales) OVER (ORDER BY month)) / LAG(sales) OVER (ORDER BY month), 1) AS growth_pct11FROM monthly12ORDER BY month;
Output
monthsalesprevdiffgrowth_pct
2025-0136NULLNULLNULL
2025-0336636330916.7
2025-04126366-240-65.6
2025-05743126617489.7
2025-06310743-433-58.3
2025-07820310510164.5
2025-08626820-194-23.7
2025-0997762635156.1
2025-10789977-188-19.2
2025-11104278925332.1
2025-125881042-454-43.6
11 rows

December is 454 lower than November, a drop of 43.6%. Don't panic yet: November had the big November sales, like Singles' Day and Black Friday, and December's data only goes up to the 26th. Always read month-over-month numbers together with what was going on.

Choose one

In the first row, January, prev, diff and growth_pct are all NULL. Why?

The previous row isn't always last month

In this step you run into the trap from lesson 2 again. Look at the March row: prev is 36, which is January's number. February had no orders, so it has no row, and LAG simply takes the row above, which is January. "March grew 916.7% on last month" is wrong.

The fix is to take the previous row's month too, check that it's exactly one month earlier, and skip the comparison if it isn't. Here each month is written as the date of its 1st, and TIMESTAMPDIFF(MONTH, earlier, later) gives how many months apart they are:

main.sql
1WITH monthly AS (2    SELECT DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start,3        SUM(amount) AS sales4    FROM orders5    WHERE status = 'paid'6    GROUP BY month_start7),8paired AS (9    SELECT month_start, sales,10        LAG(month_start) OVER (ORDER BY month_start) AS prev_month,11        LAG(sales) OVER (ORDER BY month_start) AS prev_sales12    FROM monthly13)14SELECT month_start, sales,15    CASE WHEN TIMESTAMPDIFF(MONTH, prev_month, month_start) = 1 THEN prev_sales END AS prev16FROM paired17ORDER BY month_start18LIMIT 4;
Output
month_startsalesprev
2025-01-0136NULL
2025-03-01366NULL
2025-04-01126366
2025-05-01743126
4 rows

March's prev is now NULL: the row before is January, 2 months earlier, so it isn't "last month". A more thorough fix is to fill in the missing months with 0 first, which lesson 10 covers.

Choose one

What does DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) turn 2025-03-14 into?

Year over year

In this step you meet year-over-year change: this November compared with last November. For a peak that comes every year, like the big November sales, comparing with the month before tells you nothing. Comparing with the same month last year is fair.

In a table sorted by month, the same month last year is 12 rows up. The second argument of LAG is how many rows up to look:

1LAG(sales, 12) OVER (ORDER BY month) AS last_year

The same condition as month over month applies: every month needs a row, with not a single month missing, or "12 rows up" isn't the same month last year. Our data only covers 2025, so last_year is all NULL. Once next year's data arrives, this column will have values.

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

A table of totals by quarter has 4 rows per year. To compare with the same quarter last year, what's the second argument of LAG?

1LAG(sales, ) OVER (ORDER BY quarter_start) AS last_year

How long until each person comes back

In this step you compare each row with the one before it for every customer: how many days between this order and their previous one. Add PARTITION BY user_id, and each person is sorted separately, so LAG only looks up within their own orders:

main.sql
1WITH paid AS (2    SELECT id, user_id, order_date3    FROM orders4    WHERE status = 'paid'5)6SELECT user_id, order_date,7    DATEDIFF(order_date, LAG(order_date) OVER (PARTITION BY user_id ORDER BY order_date, id)) AS gap8FROM paid9WHERE user_id = 1210ORDER BY order_date;
Output
user_idorder_dategap
122025-03-30NULL
122025-04-1415
122025-05-1733
122025-08-2297
122025-09-0817
122025-09-2113
122025-11-0848
122025-11-2618
122025-12-2327
9 rows

Lara (user 12) bought 9 times in the year, mostly two weeks to a month apart, except for a 97-day gap from May to August. Everyone's first order has a gap of NULL, because there's no order before it.

orders
user_idorder_dategap
122025-03-30NULL
122025-04-1415
122025-05-1733
262025-07-29NULL
262025-09-1447
PARTITION BY user_id: look one row up within each person's own orders
Exercise 1

Customers who come back often

For each person, work out the average number of days between two paid orders, and keep only people with at least 4 gaps (that is, at least 5 purchases). Three columns: user_id, avg_gap (rounded to 1 decimal place) and n (the number of gaps), sorted by avg_gap from smallest to largest, with ties sorted by user_id.

It should print
user_idavg_gapn
2428.04
2630.54
1233.58
1138.56
939.84
442.34
2342.84
644.36
8 rows
exercise1.sql
1WITH gaps AS (2    SELECT user_id,3        DATEDIFF(order_date, LAG(order_date) OVER (PARTITION BY user_id ORDER BY order_date, id)) AS gap4    FROM orders5    WHERE status = 'paid'6)7SELECT user_id8FROM gaps9GROUP BY user_id;
Output
Press Run or Ctrl+Enter

Looking ahead: the last order

In this step you use LEAD. It works the other way from LAG: it takes the next row. Among a person's orders, the one where LEAD(order_date) is NULL has no order after it: it's their last order.

Someone whose last order was long ago and who never came back may be lost as a customer. Find the regulars whose last order was before September 1:

main.sql
1WITH next_orders AS (2    SELECT user_id, order_date,3        LEAD(order_date) OVER (PARTITION BY user_id ORDER BY order_date, id) AS next_order4    FROM orders5    WHERE status = 'paid'6)7SELECT u.name, n.order_date AS last_order8FROM next_orders AS n9JOIN users AS u ON u.id = n.user_id10WHERE n.next_order IS NULL11    AND n.order_date < '2025-09-01'12ORDER BY n.order_date;
Output
namelast_order
Gabi2025-07-08
Otto2025-07-19
Bruno2025-08-07
Diego2025-08-30
4 rows

These 4 people haven't ordered for almost 4 months. Sending them a "we miss you" coupon costs much less than winning a new customer.

Put in orderDrag, or use the arrows

Put these lines in order to make a query that runs: after each of Felipe's orders (user 6), how many days until his next one?

  1. WHERE user_id = 6 AND status = 'paid'
  2. ORDER BY order_date;
  3. SELECT order_date,
  4. DATEDIFF(LEAD(order_date) OVER (ORDER BY order_date), order_date) AS wait
  5. FROM orders
Should print
order_date | wait
2025-03-30 | 13
2025-04-12 | 87
2025-07-08 | 28
2025-08-05 | 26
2025-08-31 | 91
2025-11-30 | 21
2025-12-21 | NULL

What you learned

  • Month over month: sales - LAG(sales) OVER (ORDER BY month), and divide by LAG(sales) for the growth rate. The first row has no row before it, so it's NULL.
  • The previous row isn't always last month: if a month is missing, LAG jumps over it. Take the previous row's month too and check it with TIMESTAMPDIFF(MONTH, …), or fill in the missing months first.
  • Year over year: LAG(sales, 12) (by month) or LAG(sales, 4) (by quarter), as long as no rows are missing.
  • To compare within each person: LAG(…) OVER (PARTITION BY user_id ORDER BY order_date). AVG and COUNT(col) skip the NULL of the first order.
  • LEAD takes the next row. The row where LEAD is NULL is the last one, which helps you find customers who haven't been back for a long time.
Practise what this lesson taught#023LAG()Change from last monthBasic#024LAG() + ROUND()Month-over-month growthMini challenge#015LAG() + MONTH()Two months in a rowMini challengeAll 50 SQL problems →