← Back to SQL, page 15

sql-0299 · Medium mid

Which day had the biggest increase in sales over the previous day?

Compute the change with amount - LAG(amount) OVER (ORDER BY day) in a subquery, then order by that change descending and take the first row. Exclude the NULL change of the first day, and decide whether 'previous day' means the previous row or the previous calendar day.

Full answer
sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
sql
SELECT day, change FROM (
  SELECT day, amount - LAG(amount) OVER (ORDER BY day) AS change FROM daily_sales
) WHERE change IS NOT NULL
ORDER BY change DESC LIMIT 1;
daychange
2026-03-09140

9 March rose by 140 over the previous row, 6 March. Note that the previous row is three days earlier here, because 7 and 8 March have no sales. If the business means the previous calendar day, fill the calendar with zeros first; then 9 March would compare with a zero on 8 March.

The window cannot be used directly in ORDER BY ... LIMIT with a filter on it, so the subquery computes the change first. SQLite does allow ORDER BY amount - LAG(amount) OVER (...) directly, but filtering out the NULL still needs the subquery.

sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);

SELECT day, change FROM (
  SELECT day, amount - LAG(amount) OVER (ORDER BY day) AS change FROM daily_sales
) WHERE change IS NOT NULL
ORDER BY change DESC LIMIT 1;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • LAG gives the previous row's value
  • Compute the change in a subquery, then sort
  • Exclude the first row's NULL change
  • Previous row may not be the previous calendar day

Common mistakes

  • Sorting with NULL changes first
  • Ignoring missing days

Follow-ups

  • How would you find the biggest drop?
  • How would you report the top increase per month?

Tips

  • Mention the missing-day definition