Skip to content

Compute a running total (cumulative sum) snippet

A running total sums every row up to and including the current one — the classic window-function job, no self-join and no subquery.

A running total sums every row up to and including the current one — the classic window-function job, no self-join and no subquery. The trap hides in the frame: with ORDER BY inside OVER, the default frame is RANGE UNBOUNDED PRECEDING, and RANGE treats peer rows (same sort key) as one step — tie rows all get the same total. ROWS UNBOUNDED PRECEDING makes the accumulation row-by-row, which is almost always what a running total means. Skip the ORDER BY entirely and you get the grand total on every row instead.

Runnable recipe · 1 languages
Files & Datasqlwindow-functionssumaggregatecumulative

Every language

1 implementations, copy-ready. One at a time with syntax highlighting, or all inline.

SQLSQLrunnable
SELECT
    day,
    amount,
    SUM(amount) OVER (
        ORDER BY day
        ROWS UNBOUNDED PRECEDING
    ) AS running_total
FROM daily_sales
ORDER BY day;

Try it in the playground: add a duplicate day and watch the RANGE default give both rows the same total; ROWS fixes the accumulation. Moving 7-day window: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW.

Run in the SQL playground →

Keep going

Read the sql-window-functions cheatsheet →