Calculate Month-over-Month Revenue Change per Product
Return the ten largest increases in a product's revenue from one month it sold in to the next.
The challenge runs on the SQLabHub practice database (SQLite) and uses the orders and order_items tables. You can solve it in the browser, with nothing to install.
Why this question comes up
The buying team wants the biggest month-on-month sales jumps for any product, to understand what caused them: a promotion, a review, a seasonal effect.
The task
Find the 10 biggest month-over-month revenue increases for any product: the product, the previous month it sold in, the month it sold in, that month's revenue and the increase.
A correct answer returns 10 rows with 5 columns: product_id, prev_month, month, revenue, growth.
Tables used in this challenge
orders 200 rows
id INTEGER (PK) · user_id INTEGER · total REAL · discount REAL · item_count INTEGER · status TEXT · order_date TEXT · shipped_date TEXT · shipping_city TEXT · shipping_country TEXT
| id | user_id | total | discount | item_count | status | order_date | shipped_date | shipping_city | shipping_country |
|---|---|---|---|---|---|---|---|---|---|
order_items 494 rows
id INTEGER (PK) · order_id INTEGER · product_id INTEGER · quantity INTEGER · unit_price REAL · subtotal REAL
| id | order_id | product_id | quantity | unit_price | subtotal |
|---|---|---|---|---|---|
The first rows of each table are shown. See how all the tables relate on the database schema page.
Expected output
| product_id | prev_month | month | revenue | growth |
|---|---|---|---|---|
The complete result: 10 rows. This is the output of the model solution on the practice database.
What you practise
- Filtering rows with a WHERE condition
- Testing for missing values with IS NULL and IS NOT NULL
- Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
- Grouping by more than one column to get a row per combination
- Combining rows from two tables on a matching key with an inner join
- Naming an intermediate result with a WITH clause and reading from it
- Working with dates in SQLite: strftime, julianday and DATE
- Reading the previous row's value with LAG()
- Restarting a window calculation for each group with PARTITION BY
- Sorting the result with ORDER BY
- Returning only the first rows with LIMIT
- Deriving a new column from an expression and naming it with an alias
Hint and approach
Try the challenge first. Open these only when you need them.
Show the hint
Total revenue per product and month in a CTE, then LAG() over each product's months; drop the first month of each product, where there is nothing to compare with
Show the step-by-step approach
How the model solution is built, in the order the database evaluates it:
- Define a common table expression named
monthly:- Read from the
order_itemstable. - Join
ordersonorder_items.order_id=orders.id. - Group the rows by
order_items.product_idandmonth(the year-month oforders.order_date), so the result has one row for each combination. - For each group, compute
SUM(order_items.subtotal).
- Read from the
- Define a common table expression named
growth:- Read from the
monthlyCTE. - Fetch
monthfrom the previous row withLAG(), ordered bymonth, restarting for eachproduct_id. Where there is no such row the value is NULL. - Fetch
revenuefrom the previous row withLAG(), ordered bymonth, restarting for eachproduct_id. Where there is no such row the value is NULL. - Combine those values into
growth:revenue - LAG(revenue) OVER (PARTITION BY product_id ORDER BY month).
- Read from the
- Read from the
growthCTE. - Filter in
WHERE: keep the rows wheregrowthhas a value (it is not NULL). ROUND()trims the calculated figures to a fixed number of decimals.- Sort the result by
growthdescending. - Keep only the first 10 rows with
LIMIT.
Show the model solution
WITH monthly AS (
SELECT oi.product_id, strftime('%Y-%m', o.order_date) AS month,
SUM(oi.subtotal) AS revenue
FROM order_items oi
JOIN orders o ON oi.order_id = o.id
GROUP BY oi.product_id, month
),
growth AS (
SELECT product_id, month, revenue,
LAG(month) OVER (PARTITION BY product_id ORDER BY month) AS prev_month,
revenue - LAG(revenue) OVER (PARTITION BY product_id ORDER BY month) AS growth
FROM monthly
)
SELECT product_id, prev_month, month,
ROUND(revenue, 2) AS revenue, ROUND(growth, 2) AS growth
FROM growth
WHERE growth IS NOT NULL
ORDER BY growth DESC
LIMIT 10;This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.
What to watch for
The CTE reduces order lines to one row per product and month, and LAG() partitioned by product reads the previous month. Months with no sales have no row, so the "previous month" is the last month with sales, which can be a year earlier; prev_month is in the output so you can see that. A product's first month has no previous one and is filtered out.
- LAG(). LAG() returns NULL for the first row of each partition, and any arithmetic with that NULL is NULL too. Supply a default as the third argument if you need a number.
- PARTITION BY. PARTITION BY is not GROUP BY: it keeps every row and only decides which rows a window function looks at.
- CTE (WITH). A CTE exists only for the single statement it is attached to. It is not a temporary table and cannot be reused by the next query.
Related SQL challenges
- Calculate Week-over-Week Revenue ChangeSimilar levelHard
- Measure Monthly Revenue Volatility per ProductSimilar levelHard
- Build a Monthly Revenue Report Excluding Cancelled OrdersEasierMedium
- Calculate Day-over-Day Revenue Growth in PercentSimilar levelHard
- Find the Longest Streak of Rising Daily RevenueSimilar levelHard
Same technique, other tables
More practice on this pattern with different columns:
Keep learning
- Lesson: LAG & LEAD
- Lesson: Window Functions
- Lesson: CTEs (WITH Clause)
- Lesson: INNER JOIN
- All SQL practice challenges, by difficulty and topic
- SQL interview questions with answers
- SQL Playground: run any query on the same database