HardSQL challenge #292WINDOW FUNCTIONLAGAGGREGATION

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.

Solve This SQL Challenge

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

First 3 rows of the orders table
iduser_idtotaldiscountitem_countstatusorder_dateshipped_dateshipping_cityshipping_country
143321.680.259cancelled2024-04-24NULLDelhiIndia
2810.520.191delivered2024-03-152024-03-20ColumbusUSA
3136181.190.085delivered2023-02-152023-02-18ChicagoUSA

order_items 494 rows

id INTEGER (PK) · order_id INTEGER · product_id INTEGER · quantity INTEGER · unit_price REAL · subtotal REAL

First 3 rows of the order_items table
idorder_idproduct_idquantityunit_pricesubtotal
1176549.99249.95
2182332.9998.97
3165179.9979.99

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
product_idprev_monthmonthrevenuegrowth
382023-062023-0814191290
1062023-052023-061374916
902022-072022-081745698
902023-112023-121047698
1142023-052023-061495598
102022-092022-10745596
582023-122024-06996498
1202022-022023-03549.95439.96
512024-082024-10556417
722024-042024-11699.93399.96

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:

  1. Define a common table expression named monthly:
    1. Read from the order_items table.
    2. Join orders on order_items.order_id = orders.id.
    3. Group the rows by order_items.product_id and month (the year-month of orders.order_date), so the result has one row for each combination.
    4. For each group, compute SUM(order_items.subtotal).
  2. Define a common table expression named growth:
    1. Read from the monthly CTE.
    2. Fetch month from the previous row with LAG(), ordered by month, restarting for each product_id. Where there is no such row the value is NULL.
    3. Fetch revenue from the previous row with LAG(), ordered by month, restarting for each product_id. Where there is no such row the value is NULL.
    4. Combine those values into growth: revenue - LAG(revenue) OVER (PARTITION BY product_id ORDER BY month).
  3. Read from the growth CTE.
  4. Filter in WHERE: keep the rows where growth has a value (it is not NULL).
  5. ROUND() trims the calculated figures to a fixed number of decimals.
  6. Sort the result by growth descending.
  7. 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.
Solve This SQL Challenge

Same technique, other tables

More practice on this pattern with different columns:

Keep learning