Full answer
sql
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT cur.month, cur.revenue, prev.revenue AS last_year,
ROUND(100.0 * (cur.revenue - prev.revenue) / NULLIF(prev.revenue, 0), 1) AS yoy_pct
FROM m cur
LEFT JOIN m prev ON prev.month = printf('%04d', CAST(substr(cur.month, 1, 4) AS INTEGER) - 1) || substr(cur.month, 5)
WHERE cur.month >= '2026-01'
ORDER BY cur.month;| month | revenue | last_year | yoy_pct |
|---|---|---|---|
| 2026-02 | 90 | NULL | NULL |
| 2026-03 | 130 | 100 | 30.0 |
March 2026 compares with March 2025. February 2026 has no row a year earlier, so the LEFT JOIN keeps it with NULL rather than dropping it.
The LAG version is shorter but assumes exactly 12 rows per year in order. With a missing month, LAG(revenue, 12) silently compares with the wrong month:
sql
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT month, revenue, LAG(revenue, 12) OVER (ORDER BY month) AS lag12 FROM m ORDER BY month;| month | revenue | lag12 |
|---|---|---|
| 2025-03 | 100 | NULL |
| 2025-04 | 80 | NULL |
| 2026-02 | 90 | NULL |
| 2026-03 | 130 | NULL |
Here only four months exist, so LAG finds nothing 12 rows back and returns NULL everywhere, including for March 2026, which does have a prior-year month. Fill the calendar first if you want to use LAG.
sql
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT cur.month, cur.revenue, prev.revenue AS last_year,
ROUND(100.0 * (cur.revenue - prev.revenue) / NULLIF(prev.revenue, 0), 1) AS yoy_pct
FROM m cur
LEFT JOIN m prev ON prev.month = printf('%04d', CAST(substr(cur.month, 1, 4) AS INTEGER) - 1) || substr(cur.month, 5)
WHERE cur.month >= '2026-01'
ORDER BY cur.month;
WITH m(month, revenue) AS (VALUES ('2025-03', 100), ('2025-04', 80), ('2026-02', 90), ('2026-03', 130))
SELECT month, revenue, LAG(revenue, 12) OVER (ORDER BY month) AS lag12 FROM m ORDER BY month;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Aggregate per month first
- Join each month to the same month a year earlier
- LEFT JOIN keeps months without history
- LAG(x, 12) needs a complete month series
Common mistakes
- Using LAG(12) on data with missing months
- Dividing by a NULL or zero prior value without NULLIF
Follow-ups
- How would you compute the growth percentage?
- How would you handle a fiscal year starting in April?
Tips
- Mention the missing-month risk