Calculating Running Totals & Cumulative Distributions
Build running sums and cumulative percentages for dashboards and ledgers.
In plain words
Keep adding as you go down the list, and show the total so far on every row.
Think of it like…
A bank passbook: each line shows the transaction and the balance after it, which is the running total of every transaction so far.
Where you’ve seen it
A per-account balance: SELECT account_id, txn_at, amount, SUM(amount) OVER (PARTITION BY account_id ORDER BY txn_at, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS balance FROM transactions;
Words you’ll hear
- Window frame
- Which rows around the current one are included: here, everything from the start up to the current row.
- ROWS vs RANGE
- ROWS counts physical rows; RANGE includes every row with the same ORDER BY value (peers).
- Cumulative %
- Running total divided by the grand total.
- PARTITION BY
- Restarts the running total per group, such as per account.
Visual diagram
Theory & example queries
The running total and the default-frame trap
SUM(x) OVER (ORDER BY day) already gives a running total, because adding ORDER BY to an aggregate window sets the default frame to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE treats rows with the same ORDER BY value as peers and includes all of them, so two transactions on the same timestamp both show the total after both.
For a balance that changes row by row, write the frame explicitly as ROWS and add a unique tiebreaker to ORDER BY (ORDER BY txn_at, id). Then every row gets its own, deterministic running total.
Two ₹100 deposits at the same time: SUM(amount) OVER (ORDER BY txn_at) shows 200 on both rows, while SUM(amount) OVER (ORDER BY txn_at, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) shows 100 then 200.
Cumulative percentages and performance
Divide the running total by the grand total, computed with an empty window SUM(x) OVER (), to get a cumulative share. Ordered by revenue descending, this produces a Pareto curve: the row where the share passes 80% tells you how many customers make up 80% of revenue.
Window functions compute running totals in one sorted pass. The old approach, a self join that sums every earlier row for each row, does roughly n²/2 work and becomes unusable on large tables. An index on the ORDER BY columns can save the sort.
SELECT customer_id, revenue, SUM(revenue) OVER ( ORDER BY revenue DESC, customer_id ROWS UNBOUNDED PRECEDING ) / SUM(revenue) OVER () AS cum_shareFROM customer_revenue;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative cumulative shares4 sample rows
| customer_id | revenue | cum_share |
|---|---|---|
| 8 | 5000 | 0.5 |
| 12 | 3000 | 0.8 |
| 7 | 1500 | 0.95 |
| 19 | 500 | 1 |
Note: The sample assumes revenue is numeric and the values total 10000, making 50%, 80%, 95% and 100% cumulative shares. If revenue is an integer type, cast the sums to numeric to avoid integer division.
Key takeaway: Running total ÷ SUM() OVER () = cumulative share, in a single pass.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Choose the order
Pick what "so far" means: by date for balances, by value descending for Pareto analysis. Add a unique tiebreaker.
ORDER BY txn_at, idWhen to use it & trade-offs
What it is
A running total adds each row's value to the sum of all rows before it, in a chosen order: SUM(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). A cumulative percentage divides that running total by the grand total, SUM(amount) OVER ().
Why it matters: Account balances, cumulative revenue, "how close are we to the monthly target?" and Pareto charts ("top 20% of customers bring 80% of revenue") are all running totals. Interviewers also use them to test whether you know the default window frame, which gives surprising results when values tie.
When to reach for it
- Account balances and ledgers
- Cumulative revenue against a target
- Pareto / 80-20 analysis
When to avoid or be careful
- Relying on the default RANGE frame when timestamps can tie
- Integer division when computing cumulative percentages
- Self-join running totals on large tables
Window frame choices for running totals
Strengths: Each row gets its own total, deterministic with a tiebreaker.
Watch out: Must be written explicitly.
Strengths: Shortest syntax.
Watch out: Ties share one total, which surprises people.
Strengths: Works on very old engines.
Watch out: Roughly quadratic; unusable on large tables.
Interview signals & numbers to know
When this topic comes up
- “Running total" or "cumulative sum”
- “Balance after each transaction”
- “What share of revenue comes from the top customers?”
- Window frame
- ROWS vs RANGE
Benchmarks & rules of thumb
- RANGE
- default frame when ORDER BY is present
- SUM() OVER ()
- grand total on every row
- n²/2
- row comparisons in the self-join approach
Common mistakes & follow-ups
Common interview mistakes
- Getting the same running total on tied rows because of the default RANGE frame.
- Forgetting PARTITION BY, so one account's balance continues into the next account.
- Computing a percentage with integer columns and getting 0 for every row.
Likely interviewer follow-ups
- What's the difference between ROWS and RANGE in a window frame?
- How would you compute each account's balance after every transaction?
- How would you find the smallest set of customers that makes up 80% of revenue?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Calculating Running Totals & Cumulative Distributions with hands-on SQL practice and interview Q&A.