Part 08 / Topic 3 of 10
Period-over-period growth
"How did this month compare to last month?" is LAG on an aggregated CTE:
WITH monthly AS (
SELECT date_trunc('month', o.order_date)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY 1
)
SELECT month, revenue,
revenue - LAG(revenue) OVER (ORDER BY month) AS change,
round(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS growth_pct
FROM monthly
ORDER BY month;
month | revenue | change | growth_pct
------------+---------+----------+------------
2025-01-01 | 2069.00 | |
2025-02-01 | 135.00 | -1934.00 | -93.5
2025-03-01 | 150.00 | 15.00 | 11.1
2025-04-01 | 1709.00 | 1559.00 | 1039.3
(4 rows)
Every piece has appeared before: date_trunc buckets, LAG reaches back, NULLIF guards the division, and the first month's NULLs say honestly "nothing to compare against". Year-over-year is the same query with LAG(revenue, 12) on a monthly series — the offset argument earning its keep.
🧪 Quick quiz — answer from memory, then check.
- Why NULLIF in the growth formula?
- How does month-over-month become year-over-year?
Show the answers
- A zero-revenue previous month would make the division explode; NULLIF turns it into an honest NULL instead.
LAG(revenue, 12)— compare against the row 12 months back.
Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.