Recipe · SQL recipes

SQL running total: cumulative sums and balances with SUM OVER

Use SUM(amount) OVER with PARTITION BY to separate groups, ORDER BY to set the order and ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to accumulate row by row.

Before continuing: This entry is part of the window functions guide. If you are new to the topic, start with OVER.

Basic query

SQLite · running total by account and transaction
SELECT count, id, date, amount_cents,
       SUM(amount_cents) OVER (
         PARTITION BY count
         ORDER BY date, id
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS cumulative_cents
FROM movements_cumulative_demo
ORDER BY count, date, id;
Set up the example data

The nine transactions are stored in whole cents: 2500 means 25.00 currency units. Debits are negative. Two of account A's transactions share the same date and time, so their id sets the order in which they apply. In this demo, id is unique and breaks the tie consistently, but on its own it does not represent the transaction date.

Dates are stored as fixed-width text and all use the same time zone. For real data with different time zones, normalise the timestamp first. The amount is NOT NULL because every posted transaction must have a known value.

SQLite · nine transactions
CREATE TABLE movements_cumulative_demo (
  id INTEGER PRIMARY KEY,
  count TEXT NOT NULL,
  date TEXT NOT NULL,
  amount_cents INTEGER NOT NULL
);
INSERT INTO movements_cumulative_demo VALUES
  (1, 'A', '2026-09-30 18:00:00', 10000),
  (2, 'A', '2026-10-01 09:00:00',  2500),
  (3, 'A', '2026-10-01 09:00:00', -1000),
  (4, 'A', '2026-10-02 10:00:00',  4000),
  (5, 'A', '2026-10-03 12:00:00',  -500),
  (6, 'B', '2026-09-30 09:00:00',  7000),
  (7, 'B', '2026-10-01 09:00:00', -2000),
  (8, 'B', '2026-10-02 10:00:00',  1000),
  (9, 'B', '2026-10-02 10:00:00',     0);

Download data and queries (.sql)

The file is ready for an empty SQLite database and contains the same examples as this guide. Run it once on a test connection that supports window functions. The course's teaching engine does not support all of these constructs, so use SQLite to reproduce the full case.

SUM adds up the amounts of the transactions inside the window. PARTITION BY separates A from B. Ordering by date, then id, puts first the transaction that must be applied first; ROWS covers everything from the start of the account up to the current transaction.

The final ORDER BY sorts what you see; the ORDER BY inside OVER drives the calculation. Keeping both stops the report from looking jumbled even when its figures are right.

Result: running total in cents

AccountidAmountRunning total
A11000010000
A2250012500
A3-100011500
A4400015500
A5-50015000
B670007000
B7-20005000
B810006000
B906000

Follow the two paths: A goes from 10000 to 12500 and drops to 11500 after the debit. B starts at 7000 without carrying over A's final 15000. B's last transaction has an amount of zero, so its running total stays at 6000.

How it works

  • SUM(amount) OVER computes the total without losing the individual transactions.
  • PARTITION BY count keeps the accounts separate.
  • ORDER BY date, id fixes the sequence and breaks ties.
  • ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW covers everything from the first transaction to the current one.

Cases that change the result

Why declare ROWS and break date ties

Account A has two transactions at 09:00 on 1 October. If you sort by date alone and leave out the frame, SQLite's default frame includes every row tied on that value. That can be useful for a total at each point in time, but seeing the balance after each transaction is a different goal.

SQLite · comparing the total per timestamp with the total per transaction
SELECT id, amount_cents,
       SUM(amount_cents) OVER (
         ORDER BY date
       ) AS cumulative_by_date,
       SUM(amount_cents) OVER (
         ORDER BY date, id
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS cumulative_by_movement
FROM movements_cumulative_demo
WHERE count = 'A'
ORDER BY date, id;

Same timestamp, two different answers

idAmountBy dateBy transaction
1100001000010000
225001150012500
3-10001150011500
440001550015500
5-5001500015000

Declaring ROWS is not enough if the order is still tied: you still need to decide which transaction takes which position. Ordering by date and then id makes that decision explicit. The reference on ROWS and RANGE explains the frame types; here, the difference between them changes a real report.

Showing October without losing earlier history

Apply the date filter after computing the running total if you want to keep the transactions from before the visible period. A CTE computes the balances first; the outer SELECT then picks which rows to show.

SQLite · October with the opening balance kept
WITH balances AS (
  SELECT count, id, date, amount_cents,
         SUM(amount_cents) OVER (
           PARTITION BY count
           ORDER BY date, id
           ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
         ) AS cumulative_cents
  FROM movements_cumulative_demo
)
SELECT count, id, date, cumulative_cents
FROM balances
WHERE date >= '2026-10-01' AND date < '2026-11-01'
ORDER BY count, date, id;

The first visible row for A, id 2, has a running total of 12500. If you put the October filter inside the query that computes SUM OVER, that row would show 2500, because you would have excluded September's 10000. B would start at −2000 instead of 5000. Both queries can be valid, but they answer different questions: the balance including history, or the net movement for the period.

A range that is closed at the start and open at the end includes any time in October. If you need a refresher on that pattern, see how to filter between two dates.

Resetting the running total every month, on purpose

When the report asks how much moved within each month, the month must be part of the partition. Include the year too: partitioning by month number alone would lump together Octobers from different years.

SQLite · running total reset by account and month
SELECT count, id, date,
       SUM(amount_cents) OVER (
         PARTITION BY count, strftime('%Y-%m', date)
         ORDER BY date, id
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS cumulative_month_cents
FROM movements_cumulative_demo
ORDER BY count, date, id;

In October, A shows 2500, 1500, 5500 and 5000. The last value is October's net movement, not the closing balance for the whole history. strftime is how SQLite builds the year-month key; other engines use different functions.

Daily running total: aggregate before applying the window

If you want one row per day, group each day's transactions first and then accumulate the daily figures. Applying a window directly to transactions and then hiding rows with DISTINCT does not define this granularity correctly.

SQLite · daily total and running total over the history
WITH daily AS (
  SELECT count, substr(date, 1, 10) AS day,
         SUM(amount_cents) AS daily_amount_cents
  FROM movements_cumulative_demo
  GROUP BY count, substr(date, 1, 10)
)
SELECT count, day, daily_amount_cents,
       SUM(daily_amount_cents) OVER (
         PARTITION BY count ORDER BY day
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS cumulative_cents
FROM daily
ORDER BY count, day;

A's 1 October appears once, with a daily amount of 1500 and a running total of 11500. B keeps 2 October as a single day with an amount of 1000. A day with no transactions does not appear in this result: to show it you need a calendar table, as in the guide on the daily moving average.

Adapting it to PostgreSQL, MySQL and SQL Server

The main query uses a window structure available in PostgreSQL, MySQL 8.0 or later and SQL Server 2012 or later. On those engines, set up the data with proper date and amount types and keep the unique ordering, the partition and the frame. The downloadable scripts were run in SQLite; these variants have not been tested on servers for the other engines.

Month key for adapting the monthly reset

EngineSample expression on a typed date
SQLitestrftime('%Y-%m', date)
PostgreSQLdate_trunc('month', date)
MySQLDATE_FORMAT(date, '%Y-%m')
SQL ServerYEAR(date), MONTH(date) as two PARTITION BY expressions

Avoid mixing a date type with strings whose format depends on the session. The point of adapting it is to keep track of which transactions belong to each month, not to copy a SQLite function word for word.

How to check it

Checks that catch a misleading running total

  • Identity and order: check which columns separate the accounts and which key breaks ties. A JOIN that multiplies transactions also multiplies their amounts.
  • Scope: state whether you are adding up the whole history, the period or the month. The filter must match that definition.
  • Unknown amounts: SUM skips NULL, which does not prove the total is complete. Find incomplete transactions or decide how to treat them before publishing; do not turn them into zero without a rule.
  • Currency and precision: do not accumulate amounts in different currencies within one partition. Use a suitable exact type and check its limits against the largest possible sum.
  • Reconciliation: the last running total for each account must match SUM over the same history. In this example, A ends at 15000 and B at 6000.

On a large table, an index on account, date and id is worth investigating. It does not guarantee the engine will avoid sorting or that the query will be faster: check the plan with EXPLAIN and measure with representative data. Keep enough history that the index never tempts you to change what the balance means.

SQLite · first time the threshold is crossed
WITH balances AS (
  SELECT count, id, date, amount_cents,
         SUM(amount_cents) OVER (
           PARTITION BY count
           ORDER BY date, id
           ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
         ) AS cumulative_cents
  FROM movements_cumulative_demo
), candidates AS (
  SELECT count, id, date, cumulative_cents,
         ROW_NUMBER() OVER (
           PARTITION BY count ORDER BY date, id
         ) AS rn
  FROM balances
  WHERE cumulative_cents >= 15000
)
SELECT count, id, date, cumulative_cents
FROM candidates
WHERE rn = 1
ORDER BY count;

Exercise result

AccountidDateRunning total
A42026-10-02 10:00:0015500

The full balance is computed first. Then the crossings are filtered and the candidates numbered. Filtering individual amounts before accumulating would remove transactions you need; looking for the MAX of the balance would find a size, not the first transaction that reaches the goal.