How do you compute a running total?
A running total is SUM with OVER and ORDER BY, adding everything from the start of the group to each row. PARTITION BY separates accounts. The default RANGE frame adds rows with equal sort values together, so a unique key goes into ORDER BY, or ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is used. Only completed operations are counted and money is kept in NUMERIC.
SQL · Window functions
The transaction history exists but the balance at each moment is not stored. How to rebuild it with one query?
An account shows the balance after each operation, while the database holds only the operations. To check that the balance never went negative or to find the moment of a mismatch, you have to compute "the sum from the first operation to this one". A running total does this with a window function, without loops and without a self-join.
How it works and why. SUM(…) OVER (… ORDER BY …) adds the values from the start of the group to the current row. If OVER has an ORDER BY and no frame is given, the window for each row is "from the start of the group to the current row and all its peers by the sort" (by the standard RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). This matters, and the consequences are below. The sample data: the completed operations of account 10, where a deposit adds and a withdrawal subtracts.
History and balance
| id | type | amount |
|---|---|---|
| 1 | deposit | 500 |
| 2 | withdrawal | 200 |
| 3 | deposit | 100 |
| 4 | withdrawal | 450 |
| id | balance |
|---|---|
| 1 | 500 |
| 2 | 300 |
| 3 | 400 |
| 4 | -50 |
SELECT id, type, amount,
SUM(CASE WHEN type = 'deposit' THEN amount ELSE -amount END)
OVER (PARTITION BY account_id
ORDER BY created_at, id) AS balance
FROM transactions
WHERE account_id = 10 AND status = 'completed'
ORDER BY created_at, id;
-- balance: 500, 300, 400, -50
Check by hand: 500, 500 − 200 = 300, 300 + 100 = 400, 400 − 450 = −50. A finding is already visible here: the fourth withdrawal should have been rejected, yet the balance went below zero. Such moments are convenient to find with a CTE:
-- the moment the balance went negative: id 4
WITH h AS (
SELECT id, created_at,
SUM(CASE WHEN type = 'deposit' THEN amount ELSE -amount END)
OVER (PARTITION BY account_id ORDER BY created_at, id) AS balance
FROM transactions
WHERE account_id = 10 AND status = 'completed'
)
SELECT id, created_at, balance FROM h WHERE balance < 0;
Another scenario: compare the last value of the running total with the current accounts.balance. If they differ, somewhere in the history an operation is lost or doubled.
The trap of the default frame. If several rows have the same value in ORDER BY, the default frame adds them all at once. Take three operations: a deposit of 100 at 10:00, then two of 50 and 25 at 10:05 (the same time).
Equal time in ORDER BY
| id | time | amount | running |
|---|---|---|---|
| 1 | 10:00 | 100 | 100 |
| 2 | 10:05 | 50 | 175 |
| 3 | 10:05 | 25 | 175 |
| id | time | amount | running |
|---|---|---|---|
| 1 | 10:00 | 100 | 100 |
| 2 | 10:05 | 50 | 150 |
| 3 | 10:05 | 25 | 175 |
The left result should look suspicious: the intermediate balance 175 in both rows is untrue: after row 2 it should be 150. There are two fixes: add a unique key to ORDER BY or specify a row frame.
-- the default frame: rows with the same created_at go together
SUM(amount) OVER (ORDER BY created_at)
-- an explicit row frame: each row is added separately
SUM(amount) OVER (ORDER BY created_at, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
-- a moving sum over the last three rows
SUM(amount) OVER (ORDER BY created_at, id
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
The default frame and a row frame
ORDER BY created_at
Rows equal in time are computed together, the intermediate balance is the same. A test comparing with the real balance may diverge.
ORDER BY created_at, id
A unique order gives one row per step. The balance after every operation is reproduced exactly.
Limits and alternatives. For moving sums and averages the frame is set explicitly: by rows ROWS BETWEEN 2 PRECEDING AND CURRENT ROW (the last three rows), by time RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW (the last three days). ROWS counts physical rows, RANGE a logical range of sort values, including peers. PostgreSQL also has GROUPS. Money uses NUMERIC, not FLOAT, otherwise the sums accumulate error. If the history is large, a running total should not be computed on every request but balance snapshots stored: for a test, a query is enough.
Typical mistakes.
ORDER BYby time without a unique key: equal rows get the same sum.- Forgetting
PARTITION BY account_id: the balance accumulates across all accounts together. - Adding all operation types with a plus sign: a withdrawal must subtract (
CASE). - Including failed and cancelled operations: the balance is counted only over completed ones.
- A filter by balance in the
WHEREof the same query: a CTE is needed.
Check yourself
Account operations: +500, −200, +100, −450. What is the balance after each, and what does it hint at to a tester?
Answer
500, 300, 400, −50. The balance went negative after the last operation. If overdraft is forbidden by the requirements, the withdrawal of 450 should have been rejected, and that is a bug candidate.
Why does SUM(amount) OVER (ORDER BY created_at) give the same result for two rows with the same time?
Answer
The default RANGE frame includes all rows equal to the current one by ORDER BY, so they are computed together. For every row to be added separately, add a unique key to ORDER BY or specify ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.