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,
SUM(amount) OVER (ORDER BY julianday(day) RANGE BETWEEN 6 PRECEDING AND CURRENT ROW) AS last_7_days,
SUM(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS last_7_rows
FROM daily_sales ORDER BY day;| day | amount | last_7_days | last_7_rows |
|---|---|---|---|
| 2026-03-01 | 120 | 120 | 120 |
| 2026-03-02 | 80 | 200 | 200 |
| 2026-03-03 | 150 | 350 | 350 |
| 2026-03-05 | 90 | 440 | 440 |
| 2026-03-06 | 60 | 500 | 500 |
| 2026-03-09 | 200 | 500 | 700 |
On 9 March, the frame covers 3 to 9 March, so it sums 150, 90, 60 and 200 even though only four of those seven days have rows. A ROWS frame of 6 PRECEDING would instead reach back six rows, to 1 March.
PostgreSQL can use the date type directly:
sql
SELECT day, SUM(amount) OVER (ORDER BY day::date RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW) AS last_7_days
FROM daily_sales ORDER BY day;| day | last_7_days |
|---|---|
| 2026-03-01 | 120 |
| 2026-03-02 | 200 |
| 2026-03-03 | 350 |
| 2026-03-05 | 440 |
| 2026-03-06 | 500 |
| 2026-03-09 | 500 |
RANGE with an offset requires exactly one ORDER BY expression of a numeric or date type. It is the cleanest way to write calendar-based rolling windows without generating a calendar first.
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,
SUM(amount) OVER (ORDER BY julianday(day) RANGE BETWEEN 6 PRECEDING AND CURRENT ROW) AS last_7_days,
SUM(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS last_7_rows
FROM daily_sales ORDER BY day;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- RANGE offsets are measured in ORDER BY values
- Order by a numeric day value for calendar windows
- Missing days are handled correctly
- PostgreSQL supports interval offsets on dates
Common mistakes
- Using ROWS and calling it a 7-day window
- Ordering by a text date with a numeric offset
Follow-ups
- How would you compute a rolling 30-day distinct user count?
- Why does RANGE need a single ORDER BY expression?
Tips
- Contrast with ROWS on the same data