# How to calculate month-over-month growth in SQL

Source: https://sqlstreak.com/sql/how-to/month-over-month-growth · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**Short answer:** Total per month, then use `LAG(total) OVER (ORDER BY month)` to put the previous month on the same row. Growth is `100.0 * (total - previous) / previous`. For year over year, compare with `LAG(total, 12)`.

**The task:** Compare each month with the one before: the change and the percent change.

### Minutes listened, month over month

```sql
WITH monthly AS (
  SELECT SUBSTR(CAST(played_on AS TEXT), 1, 7) AS month,
         SUM(minutes) AS minutes
  FROM plays
  GROUP BY 1
)
SELECT month, minutes,
       LAG(minutes) OVER (ORDER BY month) AS previous,
       ROUND(100.0 * (minutes - LAG(minutes) OVER (ORDER BY month))
             / LAG(minutes) OVER (ORDER BY month), 1) AS growth_pct
FROM monthly
ORDER BY month;
```

Result (both engines):

| month | minutes | previous | growth_pct |
| --- | --- | --- | --- |
| 2026-01 | 12626 | NULL | NULL |
| 2026-02 | 29230 | 12626 | 131.5 |
| 2026-03 | 48315 | 29230 | 65.3 |
| 2026-04 | 22195 | 48315 | -54.1 |

### Growth per group

Sign-ups per source and month, compared with the same source's previous month.

```sql
WITH monthly AS (
  SELECT source, SUBSTR(CAST(signed_up_on AS TEXT), 1, 7) AS month, COUNT(*) AS signups
  FROM users
  GROUP BY source, 2
)
SELECT source, month, signups,
       signups - LAG(signups) OVER (PARTITION BY source ORDER BY month) AS change
FROM monthly
ORDER BY source, month;
```

Result (both engines):

| source | month | signups | change |
| --- | --- | --- | --- |
| ad | 2026-01 | 17 | NULL |
| ad | 2026-02 | 12 | -5 |
| ad | 2026-03 | 28 | 16 |
| friend | 2026-01 | 17 | NULL |
| friend | 2026-02 | 37 | 20 |
| friend | 2026-03 | 37 | 0 |
| podcast | 2026-01 | 14 | NULL |
| podcast | 2026-02 | 23 | 9 |

(8 of 12 rows)

## How it works

- `WITH monthly AS (…)`: First, one row per month with its total.
- `LAG(minutes) OVER (ORDER BY month)`: The previous month's total on the current row; NULL for the first month.
- `100.0 * (minutes - previous) / previous`: The percent change. 100.0 keeps it decimal; the first month is NULL because there's nothing to compare.

## Variations

### Year over year

With several years of data, `LAG(minutes, 12) OVER (ORDER BY month)` reaches back twelve months, as long as no month is missing. Fill gaps with a generated calendar first.

### Avoid dividing by zero

If a month can be 0, wrap the divisor: `NULLIF(LAG(minutes) OVER (…), 0)`.

## Common mistakes

- Missing months: LAG takes the previous row, not the previous calendar month.
- Integer division: `100 * (a - b) / b` with whole numbers drops the decimals.
- Comparing a partial current month with full months: the last month looks like a drop.

## PostgreSQL and SQLite

Same in both engines.
