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;| day | amount | prev_max | flag |
|---|---|---|---|
| 2026-03-01 | 120 | NULL | record |
| 2026-03-02 | 80 | 120 | NULL |
| 2026-03-03 | 150 | 120 | record |
| 2026-03-05 | 90 | 150 | NULL |
| 2026-03-06 | 60 | 150 | NULL |
| 2026-03-09 | 200 | 150 | record |
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