When you need it
"Month over month revenue growth", "year over year signups", "did sales rise or fall versus last quarter", "biggest drop". Words that signal it: "growth", "change", "versus last", "month over month", "MoM", "YoY", "compared with the previous".
You always need two numbers on one row: this period and a past one. The skill is getting them side by side without losing months that had no data.
The shape of the query
with monthly as (
select date_trunc('month', ts)::date as month, sum(x) as value
from t
group by 1
)
select month, value,
lag(value) over (order by month) as prev_value,
round(100.0 * (value - lag(value) over (order by month))
/ nullif(lag(value) over (order by month), 0), 1) as growth_pct
from monthly
order by month;Step by step:
- Aggregate to one row per period in a CTE.
- Use
LAGto bring the previous row's value onto the current row. - Compute change as
(current - previous) / previous, withNULLIFguarding zero. - The first period has no previous value, so its growth is NULL. That is correct.
with monthly as (
select date_trunc('month', o.ordered_at)::date as month,
sum(oi.quantity * oi.unit_price) as revenue
from orders o
join order_items oi on oi.order_id = o.order_id
where o.status = 'completed'
group by 1
)
select month,
round(revenue, 2) as revenue,
round(lag(revenue) over (order by month), 2) as prev_revenue,
round(100.0 * (revenue - lag(revenue) over (order by month))
/ nullif(lag(revenue) over (order by month), 0), 1) as mom_pct
from monthly
order by month;Year over year can use lag(value, 12) if every month is present, or a self-join on month = month + interval '1 year' when months can be missing:
with monthly as (
select date_trunc('month', signed_up_at)::date as month, count(*) as signups
from signups
group by 1
)
select cur.month, cur.signups, prev.signups as signups_prev_month
from monthly cur
left join monthly prev
on prev.month = (cur.month - interval '1 month')::date
order by cur.month;Traps interviewers look for
- Gaps in the series.
LAGtakes the previous row, not the previous month. If March is missing, April is compared with February. Join to a calendar or use the self-join on dates. - Partial periods. The latest month is often incomplete. Comparing a half month with a full month shows a fake drop. Exclude it or compare the same day range.
- Divide by zero. A new product has zero last month. Return NULL, not an error, and say how the result should read.
- Percent versus percentage points. Going from 10 percent to 12 percent is a 2 point rise and a 20 percent rise. Use the words the prompt uses.
- Growth of a ratio. If the metric is itself a rate, compute the rate per period first, then compare. Do not average rates.
- Ordering the window by the wrong column. Order by the date bucket, never by the value.
- Partition leaks. When comparing per category, use
partition by category, or the first month of one category borrows the last month of another.
Variations
- Week over week. Same shape with
date_trunc('week', ...). - Same period last year. Join the table to itself on a one-year offset.
- Largest increase. Compute the change, then rank it. See the ranking lesson.
- Cumulative growth against a base. Divide each month by the first month using
first_value(value) over (order by month). - Moving comparison. Compare a 3-month average with the 3 months before it.
In other warehouses
- Snowflake, BigQuery, SQL Server and Databricks all have
LAG. MySQL has it from version 8. - Adding months. PostgreSQL uses
month + interval '1 month'. Snowflake and SQL Server useDATEADD(month, 1, month). BigQuery usesDATE_ADD(month, INTERVAL 1 MONTH). - BigQuery has
SAFE_DIVIDE(a, b)and Snowflake hasDIV0NULL(a, b)as shortcuts for the guarded division. DATE_TRUNChas a different argument order in BigQuery. See the dates lesson.