← Back to SQL, page 15

sql-0298 · Hard senior

How can a RANGE frame with a numeric offset count events in the last 7 days, even when some days are missing?

Order the window by a numeric day value, such as julianday(day), and use RANGE BETWEEN 6 PRECEDING AND CURRENT ROW. RANGE offsets are measured in the ORDER BY value, so the frame covers seven calendar days whether or not every day has a row. PostgreSQL also accepts interval offsets on date columns.

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;
dayamountlast_7_dayslast_7_rows
2026-03-01120120120
2026-03-0280200200
2026-03-03150350350
2026-03-0590440440
2026-03-0660500500
2026-03-09200500700

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;
daylast_7_days
2026-03-01120
2026-03-02200
2026-03-03350
2026-03-05440
2026-03-06500
2026-03-09500

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