QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Window functions

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

transactions
idtypeamount
1deposit500
2withdrawal200
3deposit100
4withdrawal450
balance
idbalance
1500
2300
3400
4-50
Figure 1. The balance after each operation. After the fourth it went negative.
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

ORDER BY created_at
idtimeamountrunning
110:00100100
210:0550175
310:0525175
ORDER BY created_at, id
idtimeamountrunning
110:00100100
210:0550150
310:0525175
Figure 2. Rows 2 and 3 share a time, so the default frame gives them the same sum 175. A unique order key separates them.

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

Wrong

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.

Right

ORDER BY created_at, id

A unique order gives one row per step. The balance after every operation is reproduced exactly.

Figure 3. For a running total the order must be unique.

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 BY by 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 WHERE of 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.

In an interview. Junior: A running total is computed by SUM with OVER and ORDER BY: everything before is added to each row within the group. This is how I rebuild an account balance at each moment from the transaction history and can find the point where it went negative or diverged from the expected one. Middle/Senior: I remember the default frame: with ORDER BY it is RANGE, so rows with the same sort value are added together. So I add a unique key to the order or write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. I count only completed operations, keep money in NUMERIC and compare the last value with the account balance.

More articles in this chapter