Skip to content

Period over period

Compare each month or week with the one before, or with the same period last year, and compute growth correctly.

Practise: 10 questions

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:

  1. Aggregate to one row per period in a CTE.
  2. Use LAG to bring the previous row's value onto the current row.
  3. Compute change as (current - previous) / previous, with NULLIF guarding zero.
  4. 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

Variations

In other warehouses

Practise period over period