Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 90/ 160
05. Window Functions & Analytical SQL

Calculating Running Totals & Cumulative Distributions

Build running sums and cumulative percentages for dashboards and ledgers.

IntermediateRunning Total · Cumulative %3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Tied timestamps, two different answers

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.

Key takeaway: Write ROWS explicitly and add a tiebreaker for true running totals.

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.

Pareto: which customers make 80% of revenue?Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  customer_id,3  revenue,4  SUM(revenue) OVER (5    ORDER BY6      revenue DESC,7      customer_id ROWS UNBOUNDED PRECEDING8  ) / SUM(revenue) OVER () AS cum_share9FROM10  customer_revenue;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative cumulative shares4 sample rows
Representative cumulative shares
customer_idrevenuecum_share
850000.5
1230000.8
715000.95
195001

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Running total ÷ SUM() OVER () = cumulative share, in a single pass.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1ORDER BY

Choose the order

Pick what "so far" means: by date for balances, by value descending for Pareto analysis. Add a unique tiebreaker.

SQL at this step
1ORDER BY2  txn_at,3  id
What to watch at this step
Tiebreaker
makes it deterministic
Tip: use ← → to move between steps

When 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

ROWS UNBOUNDED PRECEDING
Best for: Balances and row-by-row cumulative sums

Strengths: Each row gets its own total, deterministic with a tiebreaker.

Watch out: Must be written explicitly.

Default (RANGE … CURRENT ROW)
Best for: Cumulative totals per distinct date, where tied rows should share a value

Strengths: Shortest syntax.

Watch out: Ties share one total, which surprises people.

Self join summing earlier rows
Best for: Databases without window functions

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?
Interview tip: Write the frame explicitly even when the default would work, and mention why (ties). It's a small detail that signals real experience with window functions.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Calculating Running Totals & Cumulative Distributions with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Default Frame Trap with ORDER BY (RANGE UNBOUNDED PRECEDING AND CURRENT ROW)
Next topic
Moving Averages & Rolling Windows (7-Day, 30-Day Rolling Metrics)