← All Exercises

Month-over-Month Revenue Growth with LAG

basicsql~20min

Background

Finance dashboards compare every month with the month before it. Window functions expose the prior row without collapsing the result, so a self-join is unnecessary.

Problem

Given a monthly_revenue table with one row per month, return each month's revenue, the previous month's revenue, and the month-over-month growth percentage rounded to one decimal.

Input

A PostgreSQL monthly_revenue table with month date PRIMARY KEY and revenue numeric(12,2), containing at most one row per month.

Output

Columns month, revenue, previous_revenue (NULL for the first row), and mom_growth_pct rounded to one decimal, NULL when the prior revenue is zero.

Sample tests

Sample 1

Input: rows: (2026-01-01, 1000.00), (2026-02-01, 1200.00), (2026-03-01, 900.00)
Expected: 2026-01-01 | 1000.00 | NULL | NULL
2026-02-01 | 1200.00 | 1000.00 | 20.0
2026-03-01 | 900.00 | 1200.00 | -25.0

Sample 2

Input: extend the first sample with 2026-04-01 revenue 0.00 and 2026-05-01 revenue 500.00
Expected: 2026-04-01 | 0.00 | 900.00 | -100.0
2026-05-01 | 500.00 | 0.00 | NULL

Your solution

Learning objective

Use LAG with ORDER BY, compute percentages with numeric data, and handle a missing or zero predecessor safely.