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 day) AS running_total
FROM daily_sales
ORDER BY day;| day | amount | running_total |
|---|---|---|
| 2026-03-01 | 120 | 120 |
| 2026-03-02 | 80 | 200 |
| 2026-03-03 | 150 | 350 |
| 2026-03-05 | 90 | 440 |
| 2026-03-06 | 60 | 500 |
| 2026-03-09 | 200 | 700 |
Each row's running_total is the sum of all amounts up to and including that day. The ORDER BY inside OVER defines the order of accumulation; the ORDER BY at the end only decides the display order.
To restart the total each month, partition by month:
sql
SELECT day, amount,
SUM(amount) OVER (PARTITION BY substr(day, 1, 7) ORDER BY day) AS month_to_date
FROM daily_sales
ORDER BY day;| day | amount | month_to_date |
|---|---|---|
| 2026-03-01 | 120 | 120 |
| 2026-03-02 | 80 | 200 |
| 2026-03-03 | 150 | 350 |
| 2026-03-05 | 90 | 440 |
| 2026-03-06 | 60 | 500 |
| 2026-03-09 | 200 | 700 |
All the March days are in one month here, so the result matches, but the partition would reset the total on 1 April.
For running totals, writing the frame explicitly is a good habit, because the default frame (RANGE) treats rows with the same ORDER BY value as one step:
text
SUM(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)With a unique day, ROWS and RANGE give the same numbers. With duplicate keys they do not.
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 day) AS running_total
FROM daily_sales
ORDER BY day;
SELECT day, amount,
SUM(amount) OVER (PARTITION BY substr(day, 1, 7) ORDER BY day) AS month_to_date
FROM daily_sales
ORDER BY day;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- SUM(x) OVER (ORDER BY ...) gives a running total
- The window's ORDER BY sets the accumulation order
- PARTITION BY restarts the total per group
- Write the ROWS frame explicitly when order keys can repeat
Common mistakes
- Using a self join or correlated subquery for running totals on large tables
- Confusing the window ORDER BY with the query's ORDER BY
Follow-ups
- What changes if two rows have the same day?
- How would you compute a 3-day moving average?
Tips
- Mention the frame; it is what separates a good answer