SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap
A SQL running total adds each row’s value to the sum of all earlier rows. The modern way is one window function: SUM(amount) OVER (ORDER BY day, id). This guide shows per-group totals, daily cumulative sums, moving sums and percentages, plus the tie trap that silently gives wrong numbers.
- A SQL running total is
SUM(col) OVER (ORDER BY ...); addPARTITION BYto restart it for each group. - Order by a unique combination such as
day, id. Ordering by a non-unique day alone gave tied rows the same total in our test. ROWS BETWEEN 2 PRECEDING AND CURRENT ROWturns it into a 3-row moving sum.- On 20,000 rows the window function took 22 ms; the old correlated subquery took almost 8 seconds.
Cumulative revenue, account balances, stock levels, burn-down charts and “progress towards target” all need the same calculation: add up everything so far. For years this meant awkward self joins or subqueries. Modern SQL does it with one window function. We ran every query below in SQLite 3.50.4; the syntax is standard and works in PostgreSQL, MySQL 8+, SQL Server 2012+ and Oracle, although we only executed it in SQLite.
Quick answer
SELECT id, day, amount,
SUM(amount) OVER (ORDER BY day, id) AS running_total
FROM sales;
The OVER clause turns SUM from a grouping function into a window function. Instead of collapsing rows, it calculates a sum for each row over a “window” of rows: here, every row up to and including the current one in the given order.
Sample data
CREATE TABLE sales(id INTEGER PRIMARY KEY, day TEXT, region TEXT, amount INT);
INSERT INTO sales(day, region, amount) VALUES
('2026-11-01','North',100), ('2026-11-01','South',50),
('2026-11-02','North',80), ('2026-11-03','North',120),
('2026-11-03','South',70), ('2026-11-03','North',30),
('2026-11-04','South',NULL),('2026-11-05','South',90);
Several rows share the same day on purpose, and one amount is NULL. Real data looks like this, and both details change the results.
The basic running total
| id | day | amount | running_total |
|---|---|---|---|
| 1 | 2026-11-01 | 100 | 100 |
| 2 | 2026-11-01 | 50 | 150 |
| 3 | 2026-11-02 | 80 | 230 |
| 4 | 2026-11-03 | 120 | 350 |
| 5 | 2026-11-03 | 70 | 420 |
| 6 | 2026-11-03 | 30 | 450 |
| 7 | 2026-11-04 | NULL | 450 |
| 8 | 2026-11-05 | 90 | 540 |
Each row adds its amount to the total so far. The last value, 540, equals the grand total, which is a quick sanity check worth automating in tests.
The RANGE tie trap
Here is the mistake almost everyone makes once. Order by the day alone, without the id:
SELECT id, day, amount,
SUM(amount) OVER (ORDER BY day) AS range_total,
SUM(amount) OVER (ORDER BY day
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_total
FROM sales;
| id | day | amount | range_total | rows_total |
|---|---|---|---|---|
| 1 | 2026-11-01 | 100 | 150 | 100 |
| 2 | 2026-11-01 | 50 | 150 | 150 |
| 4 | 2026-11-03 | 120 | 450 | 350 |
| 5 | 2026-11-03 | 70 | 450 | 420 |
| 6 | 2026-11-03 | 30 | 450 | 450 |
With only ORDER BY, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE treats all rows with the same order value as peers and includes them all, so every row on 1 November showed 150 and every row on 3 November showed 450. The ROWS frame counts physical rows, giving a true row-by-row total, but the order of tied rows is still arbitrary unless you add a tie-breaker.
Tip: always order a running total by something unique, usually the date plus the primary key. That gives the same result with RANGE or ROWS and the same result every time you run it.
RANGE is not wrong; it answers a different question. “Total sales up to the end of each day” is exactly RANGE ordered by day. Just choose it on purpose.
Running total per group
SELECT region, day, amount,
SUM(amount) OVER (PARTITION BY region ORDER BY day, id) AS region_running
FROM sales
ORDER BY region, day, id;
| region | day | amount | region_running |
|---|---|---|---|
| North | 2026-11-01 | 100 | 100 |
| North | 2026-11-02 | 80 | 180 |
| North | 2026-11-03 | 120 | 300 |
| North | 2026-11-03 | 30 | 330 |
| South | 2026-11-01 | 50 | 50 |
| South | 2026-11-03 | 70 | 120 |
| South | 2026-11-04 | NULL | 120 |
| South | 2026-11-05 | 90 | 210 |
PARTITION BY restarts the total for every region. Use it for per-customer balances, per-account ledgers or per-month totals: PARTITION BY strftime('%Y-%m', day) in SQLite, or DATE_TRUNC('month', day) in PostgreSQL. The same idea drives ranking functions, covered in our RANK vs DENSE_RANK guide.
Daily totals, then a cumulative total
SELECT day, SUM(amount) AS daily,
SUM(SUM(amount)) OVER (ORDER BY day) AS cumulative
FROM sales GROUP BY day;
| day | daily | cumulative |
|---|---|---|
| 2026-11-01 | 150 | 150 |
| 2026-11-02 | 80 | 230 |
| 2026-11-03 | 220 | 450 |
| 2026-11-04 | NULL | 450 |
| 2026-11-05 | 90 | 540 |
SUM(SUM(amount)) looks odd, but it reads naturally once you know the order of evaluation: GROUP BY runs first and produces one daily sum per day, then the window function adds those daily sums. This is the query behind most cumulative revenue charts. Grouping is explained in our GROUP BY and HAVING guide.
Moving sums and averages
SELECT id, amount,
SUM(amount) OVER w AS sum3,
ROUND(AVG(amount) OVER w, 1) AS avg3
FROM sales
WINDOW w AS (ORDER BY day, id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW);
Changing the frame from “all earlier rows” to “the current row and the two before it” creates a rolling window. Row 4 had a 3-row sum of 250 (rows 2, 3 and 4: 50 + 80 + 120), and row 6 showed 220 with an average of 73.3. Notice row 7: its average was 50.0, because AVG ignores the NULL and divided 100 by two rows, not three. Rolling averages smooth out noisy daily data in dashboards.
Cumulative percent of total
SELECT id, amount,
ROUND(100.0 * SUM(amount) OVER (ORDER BY day, id)
/ SUM(amount) OVER (), 1) AS pct_cum
FROM sales;
An empty OVER () means “all rows”, so dividing the running total by it gives a cumulative percentage. Our data reached 18.5% after row 1, 64.8% after row 4 and 100.0% at the end. Ordering by amount descending instead gives a Pareto view: how few items make up 80% of the total.
How NULL values behave
SUM skips NULLs, so row 7 simply repeated the previous total, 450, instead of turning the whole total into NULL. That is usually what you want. If a missing amount should count as zero in other calculations, wrap it: SUM(COALESCE(amount, 0)), which gave identical totals here. Be more careful with AVG and COUNT(amount), which also skip NULLs and therefore change the denominator. Our SQL COALESCE guide covers these choices.
The old way: a correlated subquery
SELECT s.id, s.amount,
(SELECT SUM(amount) FROM sales x
WHERE x.day < s.day OR (x.day = s.day AND x.id <= s.id)) AS running
FROM sales s ORDER BY day, id;
This gives the same 100, 150, 230, … 540 results and works in very old databases without window functions, such as MySQL 5.7. A self join with GROUP BY is another variation; see our SQL self join guide. Both share the same weakness: for every row, the database sums all earlier rows again.
Speed test: window function vs subquery
We generated 20,000 rows and timed both approaches in SQLite:
| Method | Time |
|---|---|
SUM(v) OVER (ORDER BY id) |
21.9 ms |
| Correlated subquery | 7,979 ms |
The window function was about 360 times faster, because it keeps a running sum as it walks through the rows once, while the subquery re-adds earlier rows for every single row. The gap grows with every extra row, so on large tables the subquery approach is not just slower but unusable.
Real-world uses
- Account balance: running total of credits and debits per account, partitioned by account and ordered by transaction time and id.
- Inventory: stock on hand after each receipt or sale.
- Targets: cumulative sales against a monthly goal.
- Burn-down: remaining work after each completed task.
- Data checks: the final running total must equal the plain
SUM, a handy assertion in data tests.
Database support
Window functions with SUM() OVER are available in PostgreSQL, SQL Server 2012 and later, Oracle, MySQL 8.0 and later, MariaDB 10.2 and later, and SQLite 3.25 and later. The named WINDOW clause we used for the moving sum is supported in PostgreSQL, MySQL 8 and SQLite, but not in SQL Server before 2022, where you repeat the OVER (...) instead. More window patterns are in our SQL window functions tutorial.
Common mistakes
- Ordering by a non-unique column. Ties share a total under RANGE and get arbitrary order under ROWS. Add the primary key.
- Forgetting ORDER BY inside OVER.
SUM(x) OVER ()gives the grand total on every row, not a running total. - Confusing the outer ORDER BY with the window ORDER BY. The window order defines the calculation; the outer order only sorts the output.
- Filtering with WHERE after the fact. WHERE runs before the window, so it changes the totals. Filter in an outer query if you only want to display some rows.
- Ignoring NULLs in averages. Decide whether missing means zero.
Final thoughts
A SQL running total is one of the clearest wins of window functions: one readable line replaces slow self joins and subqueries. Order by a unique key, add PARTITION BY for per-group totals, change the frame for moving sums, and divide by SUM() OVER () for percentages. Check the final row against the grand total, and your cumulative reports will be both fast and right.
Frequently asked questions
How do I calculate a running total in SQL?
Use a window function: SUM(amount) OVER (ORDER BY date_column, id). Each row gets the sum of its own value and all earlier rows in that order.
How do I reset a running total for each group?
Add PARTITION BY inside the OVER clause, for example SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date, id).
Why do rows with the same date show the same running total?
With only ORDER BY, the default frame is RANGE, which includes all rows with the same order value. Order by a unique combination such as date and id, or use a ROWS frame.
How do I calculate a running total without window functions?
Use a correlated subquery or a self join that sums all earlier rows. It works in old databases but is far slower; in our test it took about 8 seconds on 20,000 rows.
How do I calculate a moving sum in SQL?
Use a ROWS frame, for example SUM(amount) OVER (ORDER BY day, id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) for a three-row moving sum.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.