SQLQuestion 09 of 14
LAG — change in sales versus the previous period
Answer out loud or in your head first, then compare.
Answer
A window function keeps the individual rows and lets you compare them with others in a set order.
SQL
-- monthly_sales(product_id, month date, revenue numeric)
-- One row per product and month
WITH comparison AS (
SELECT *, LAG(revenue) OVER (
PARTITION BY product_id ORDER BY month
) AS previous_revenue
FROM monthly_sales
)
SELECT product_id, month,
revenue - previous_revenue AS difference,
100.0 * (revenue - previous_revenue)
/ NULLIF(previous_revenue, 0) AS change_pct
FROM comparison;Pitfall: LAG means the previous row, not automatically the previous month. If periods are missing, you need to fill in a calendar. NULLIF protects against division by zero.
How did it go? Be honest — “Not yet” puts the question on your review list.