Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 94/ 160
05. Window Functions & Analytical SQL

Year-over-Year (YoY), Month-over-Month (MoM) & Day-over-Day Growth

Compute growth rates against prior periods with LAG over time partitions.

IntermediateYoY · MoM3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Put this period's number next to last period's number, then work out how much it grew in percent.

Think of it like…

A school report card that shows this term's marks next to last term's, with the change: you need both numbers for the same subject and the same kind of exam before the difference means anything.

Where you’ve seen it

Monthly revenue with MoM and YoY growth: aggregate orders per month, then LAG(revenue) OVER (ORDER BY month) for last month and LAG(revenue, 12) OVER (ORDER BY month) for the same month last year, provided every month is present.

Words you’ll hear

MoM / YoY / DoD
Compared with the previous month / the same period last year / the previous day.
Growth rate
(current − previous) / previous, usually shown as a percentage.
Seasonality
Regular yearly patterns (festive season, holidays), which is why YoY is often more meaningful than MoM.
Period-to-date
A partial current period (month to date) that must be compared with the same partial period before.

Visual diagram

Loading interactive diagram

Theory & example queries

The standard query

First aggregate to the period grain with date_trunc('month', created_at). Then LAG(revenue) OVER (ORDER BY month) gives last month's revenue on each row, and the growth rate is (revenue − prev) / NULLIF(prev, 0). Cast to numeric to avoid integer division, and multiply by 100 if you want a percentage.

For YoY on monthly data, LAG(revenue, 12) works only when the series has exactly one row for every month. A safer approach is a self join on the period shifted by a year (ON prev.month = cur.month - interval '1 year'), which is correct even when months are missing.

MoM growthQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  m AS (3    SELECT4      date_trunc('month', created_at) AS MONTH,5      SUM(amount) AS revenue6    FROM7      orders8    GROUP BY9      110  )11SELECT12  MONTH,13  revenue,14  LAG(revenue) OVER (15    ORDER BY16      MONTH17  ) AS prev,18  ROUND(19    100.0 * (20      revenue - LAG(revenue) OVER (21        ORDER BY22          MONTH23      )24    ) / NULLIF(25      LAG(revenue) OVER (26        ORDER BY27          MONTH28      ),29      030    ),31    132  ) AS mom_pct33FROM34  m;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/34
3OutputInspect the representative rows, affected-row count, plan, or command status.
Month-over-month growth3 sample rows
Month-over-month growth
monthrevenueprevmom_pct
2026-09-01900000NULLNULL
2026-10-0199000090000010
2026-11-01108900099000010

Note: Illustrative monthly revenue; the first month has no prior row, so prev and mom_pct are NULL.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: One row per period, LAG or a shifted join, and a NULLIF-protected division.

Making the comparison fair

On 19 November, "November so far" covers 19 days and October covers 31, so a naive MoM shows a big drop. Compare month-to-date with the same number of days in the previous month, or only compare complete periods.

MoM is distorted by seasonality (a festive-season month will always beat the month before), which is why business reviews lean on YoY. Also make sure both periods are measured the same way, with the same timezone, the same definition of a paid order, and refunds handled consistently.

YoY with a shifted join (robust to missing months)Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  cur.month,3  cur.revenue,4  prev.revenue AS last_year,5  (cur.revenue - prev.revenue) / NULLIF(prev.revenue, 0) AS yoy6FROM7  m cur8  LEFT JOIN m prev ON prev.month = cur.month - interval '1 year';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Year-over-year comparison3 sample rows
Year-over-year comparison
monthrevenuelast_yearyoy
2025-11-01900000NULLNULL
2026-10-0110890008800000.2375
2026-11-0111250009000000.25

Note: Assumes m contains monthly totals; values are rounded here only for readability, and missing prior-year rows produce NULL.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Compare like with like: complete or equally partial periods, same definitions.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1GROUP BY

Aggregate to the period

Group by date_trunc('day' | 'month' | 'year', ts) to get exactly one row per period (per dimension if needed).

Focus at this step

date_trunc('month', created_at)

What to watch at this step
Grain
one row per period
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Period-over-period growth compares a metric with the previous period: day over day (DoD), month over month (MoM) or year over year (YoY). Aggregate to one row per period, fetch the previous period's value with LAG() (or a join on the shifted date), then compute (current − previous) / previous.

Why it matters: "Revenue is up 12% month over month" is how most business updates start, and every analytics interview includes a version of it. The details are where people go wrong: missing months break LAG, partial months compare unfairly, and dividing by zero or NULL crashes the query.

When to reach for it

  • Monthly business reviews and KPI dashboards
  • Tracking growth per product, region or channel
  • Spotting anomalies with day-over-day changes

When to avoid or be careful

  • LAG(…, 12) for YoY on a series with missing months
  • Comparing a partial current month with a full previous month
  • Integer division or unprotected division by a zero previous value

LAG vs shifted self join vs calendar table

LAG(metric, n)
Best for: MoM or DoD on a complete, gap-free series

Strengths: Short and fast.

Watch out: Wrong if any period is missing.

Self join on the shifted period
Best for: YoY, or series that can have gaps

Strengths: Always compares the right calendar period.

Watch out: A little more code.

Calendar table + LAG
Best for: Dashboards that need every period, including empty ones

Strengths: Gap-free series with explicit zeros.

Watch out: Requires a calendar table or generate_series.

Interview signals & numbers to know

When this topic comes up

  • “Month-over-month growth”
  • “Compare with the same month last year”
  • Growth percentage
  • Seasonality
  • Month-to-date

Benchmarks & rules of thumb

(cur − prev) / prev -
growth rate
12 -
LAG offset for YoY on monthly data (gap-free only)
NULLIF(prev, 0) -
divide-by-zero guard

Common mistakes & follow-ups

Common interview mistakes

  • Running LAG on raw orders instead of on one row per month.
  • Using LAG(revenue, 12) when a month is missing, so "last year" is actually 13 months ago.
  • Showing a 40% MoM drop on the 10th of the month because the current month is only a third complete.

Likely interviewer follow-ups

  • How would you compute YoY growth if some months have no data?
  • How would you compare month-to-date revenue fairly with last month?
  • How would you compute MoM growth separately for each product category?
Interview tip: Structure the answer as aggregate, shift, divide, and mention the partial-period problem before the interviewer does. It shows you've produced real business reports.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Year-over-Year (YoY), Month-over-Month (MoM) & Day-over-Day Growth with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Top-N Records Per Category / Group
Next topic
Finding User First Purchase, Repeat Purchase & Time-Between-Orders