SQL Interview & Case Lab
Back to Business SQL Patterns

MoM, YoY, WoW — The SQL Patterns

Every BI dashboard has these. LAG() is your friend. Self-joins are not. FIND_VIDEO: search 'SQL month over month growth LAG' — recommended channel: EverSQL. Aim for 10 min or under.

8 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. Problem Overview — Examines the sales dataset schema and defines the target MoM output format.
  2. Date Extraction and Aggregation — Extracts month name and month number to aggregate total sales by month.
  3. First CTE & LAG Window Function — Wraps base aggregation in a CTE and implements LAG to pull prior month sales.
  4. Fallback Defaults in LAG — Explains why January receives current sales as its baseline using the default argument.
  5. Chained CTE & Growth Math — Builds second CTE to compute difference and percentage growth between months.
  6. Decimal Casting and Final Output — Applies DECIMAL(7, 2) casting to format final MoM growth percentage.
PDF notes

Frequently asked questions

Why use DATEPART when DATENAME already gets the month?

DATENAME returns string names like 'April' and 'January', which sort alphabetically rather than chronologically. DATEPART returns numbers (1-12) to guarantee correct temporal window ordering.

Why does January show identical total_sale and previous_sales_amount?

Because the LAG function's 3rd parameter was supplied as c.total_sale, returning the current row's sales as a fallback when no prior row exists.

Can WoW and YoY calculations use this identical pattern?

Yes. Change the date grain to week or year in DATEPART/DATENAME, partition by year/brand if necessary, and lag by 1 offset.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.