SQL Running Totals with Explicit Window Frames
Overview
A running total accumulates values from the beginning of an ordered partition through the current row. A stable sequence and clear partition key make the meaning of the total reproducible.
First example
SELECT id, team, SUM(points) OVER (PARTITION BY team ORDER BY id ROWS UNBOUNDED PRECEDING) AS runningFROM window_scores ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, "A", 90 ], [ 2, "A", 180 ], [ 3, "A", 250 ], [ 4, "A", 310 ], [ 5, "A", 360 ], [ 6, "B", 80 ], [ 7, "B", 140 ], [ 8, "B", 200 ]]How it works
Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for a row-by-row accumulation. In example one, totals reset at the team boundary. For sensor readings, SUM ignores NULL, but an entirely NULL frame would return NULL. To display only a later portion of a historical running total, compute it in a CTE before applying the outer display filter; filtering the input first changes the total.
Practical example
WITH history AS ( SELECT id, day, value, SUM(value) OVER (ORDER BY day, id ROWS UNBOUNDED PRECEDING) AS running FROM window_readings WHERE sensor = 'A') SELECT id, running FROM history WHERE day >= '2025-01-03' ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 2, 24 ], [ 3, 24 ], [ 4, 44 ]]Practice and mistakes
Change example two to filter day >= 2025-01-03 inside the CTE and compare the results. Explain why a running total should not usually use an implicit frame when business ordering has ties. PostgreSQL 17 supports this pattern; only SQLite results were executed.