← Back to SQL, page 15

sql-0296 · Medium mid

Write a query that flags each day on which sales reached a new record high.

Compare each amount with the running maximum of all earlier days: MAX(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING). A day is a record when its amount is greater than that, or when there is no earlier day. Excluding the current row from the frame is what makes the comparison meaningful.

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, amount, prev_max,
       CASE WHEN prev_max IS NULL OR amount > prev_max THEN 'record' END AS flag
FROM (
  SELECT day, amount,
         MAX(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prev_max
  FROM daily_sales
) ORDER BY day;
dayamountprev_maxflag
2026-03-01120NULLrecord
2026-03-0280120NULL
2026-03-03150120record
2026-03-0590150NULL
2026-03-0660150NULL
2026-03-09200150record

The first day is a record by definition, because the previous maximum is NULL. 3 March beats 120 and 9 March beats 150; the days in between are below the earlier peak.

A running maximum that includes the current row (... AND CURRENT ROW) would always be at least the current amount, so "amount > running max" could never be true. Ending the frame at 1 PRECEDING is the key.

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, amount, prev_max,
       CASE WHEN prev_max IS NULL OR amount > prev_max THEN 'record' END AS flag
FROM (
  SELECT day, amount,
         MAX(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prev_max
  FROM daily_sales
) ORDER BY day;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Running MAX over earlier rows tracks the previous record
  • End the frame at 1 PRECEDING
  • Treat the first row explicitly
  • Ties with the previous record are not new records

Common mistakes

  • Including the current row in the running max
  • Forgetting the first row's NULL

Follow-ups

  • How would you count records per month?
  • How would you find the longest period without a new record?

Tips

  • Explain why the frame stops before the current row