"Show the sales for each month and how much they changed from the previous month" is a standard analyst question. It combines three skills: turning dates into months, grouping, and looking at the previous row. The window function that looks backwards is called LAG, and its partner LEAD looks forward. We continue with the sales table.
Step 1: group by month
To group by month, turn each date into a month label first. In SQLite the function is strftime('%Y-%m', date), which returns text such as 2024-03. Other engines use different functions: DATE_FORMAT or MONTH in MySQL, DATE_TRUNC('month', date) in PostgreSQL, and FORMAT or EOMONTH in SQL Server. In an interview, write the idea and say which function your database uses.
SELECT strftime('%Y-%m', sale_date) AS month,
SUM(amount) AS total
FROM sales
GROUP BY month
ORDER BY month;
month | total
2024-01 | 2500
2024-02 | 3500
2024-03 | 4000
2024-04 | 3300
Sales grew from 2500 in January to 4000 in March and then fell to 3300 in April. Grouping by the label month works in SQLite and MySQL. PostgreSQL also accepts it, and SQL Server needs the full expression in GROUP BY.
Step 2: look at the previous month with LAG
LAG(total) OVER (ORDER BY month) returns the total from the row before, in month order. For the first month there is no row before, so the result is NULL. The change is the current total minus the previous total. The percent change is that change divided by the previous total, multiplied by 100.
WITH m AS (
SELECT strftime('%Y-%m', sale_date) AS month,
SUM(amount) AS total
FROM sales
GROUP BY month
)
SELECT month, total,
LAG(total) OVER (ORDER BY month) AS previous,
total - LAG(total) OVER (ORDER BY month) AS change,
ROUND(100.0 * (total - LAG(total) OVER (ORDER BY month))
/ NULLIF(LAG(total) OVER (ORDER BY month), 0), 1) AS pct_change
FROM m
ORDER BY month;
month | total | previous | change | pct_change
2024-01 | 2500 | NULL | NULL | NULL
2024-02 | 3500 | 2500 | 1000 | 40
2024-03 | 4000 | 3500 | 500 | 14.3
2024-04 | 3300 | 4000 | -700 | -17.5
February is up 1000, which is 40 percent. March is up 500, which is 14.3 percent. April is down 700, which is minus 17.5 percent. The first month shows NULL for every comparison column, and that is the honest answer, because there was no earlier month to compare to.
Why NULLIF is in there
NULLIF(previous, 0) returns NULL when the previous value is 0. Dividing by NULL gives NULL, and dividing by zero would raise an error in many databases or give nonsense. If a month had zero sales, the percent change from zero is not defined, and NULL says exactly that. This small detail is one interviewers notice.
Months with no data
There is a limit to this answer. If a month had no sales at all, it would not appear in the grouped result, and LAG would compare April to the month before the gap. In a real report you build a list of all months first, for example with a recursive query or a calendar table, and LEFT JOIN the sales to it. Mention this limit. It shows that you test your query against real life.
The best month
A simple follow-up: which month had the highest sales? Sort the grouped result and keep the first row.
SELECT strftime('%Y-%m', sale_date) AS month,
SUM(amount) AS total
FROM sales
GROUP BY month
ORDER BY total DESC
LIMIT 1;
month | total
2024-03 | 4000
March, with 4000. If two months tie for the top, LIMIT 1 hides one of them. Use RANK and keep rank 1 when ties matter, as in lesson 4.
Days between events
The same LAG idea works for dates. How many days passed between each sale of employee 6 and the one before it?
SELECT sale_date, amount,
CAST(julianday(sale_date)
- julianday(LAG(sale_date) OVER (ORDER BY sale_date)) AS INTEGER) AS days_since_previous
FROM sales
WHERE employee_id = 6
ORDER BY sale_date;
sale_date | amount | days_since_previous
2024-01-05 | 1200 | NULL
2024-02-02 | 1500 | 28
2024-02-27 | 400 | 25
2024-03-19 | 2000 | 21
2024-04-04 | 1800 | 16
There were 28 days between the first and second sale, then 25, 21 and 16. The sales are speeding up. julianday turns a date into a number of days, so subtracting two of them gives the gap. In other engines you would use DATEDIFF in MySQL and SQL Server, or subtract two dates in PostgreSQL.
Common mistakes
- Using
LAGwithoutORDER BY, so the "previous" row is not defined. - Taking the previous row from the raw sales instead of from the monthly totals, which compares a sale to a sale and not a month to a month.
- Ordering the text months wrongly. A label like
2024-03sorts correctly because the year comes first. A label such asMar 2024does not. - Calculating a percent change with whole-number division.
Your task
- Add a column with the next month's total using
LEAD. - Show a three-month moving average of the monthly totals.
- Find the month with the biggest drop compared to the month before.
- Show each employee's total for each month, and the change from their own previous month, with
PARTITION BY employee_idin theLAG.
How to check it worked
- February shows a change of 1000 and 40 percent.
- April shows minus 700 and minus 17.5 percent.
- The first month shows NULL in the previous, change and percent columns.