Running Totals & Cumulative
Cumulative Calculations in SQL
Running totals and cumulative calculations answer: "What's the total so far?" and "How does each row compare to all previous rows?" These are essential for financial reports, trend analysis, and cumulative metrics.
- Running Total —
SUM() OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) - Moving Average —
AVG() OVER (ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) - Cumulative % — Running total / grand total
- CDF —
CUME_DIST()andPERCENT_RANK()
The key distinction is ROWS vs RANGE in the window frame clause — using the wrong one produces incorrect results when there are ties.
Window Frame Clause
Every window aggregate evaluates over a frame: the slice of the partition the current row can see. The frame has three parts — a unit (ROWS, RANGE or GROUPS), a start bound and an end bound. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW starts at the partition's first row and stops at the row being computed, so each row sees every earlier row and the sum climbs monotonically. PostgreSQL's default when ORDER BY is present is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, a peer-aware frame that swallows every row sharing the same sort key. Two rows tied on sale_date therefore report identical running totals, while ROWS walks physical order and produces two distinct values. That single difference accounts for most wrong-running-total bug reports: the query is correct, the frame is not the one the author assumed.
Basic Running Total
-- Simple running total
SELECT
sale_date,
revenue,
SUM(revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM daily_sales
ORDER BY sale_date;
ℹ️
Key Insight: Always use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for a true running total. Without the frame clause, PostgreSQL defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW which includes all peers (ties in ORDER BY).
Work the numbers on a three-day series of 100, 120, 110. With ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW the cumulative column reads 100, 220, 330, because each step absorbs exactly one row. Replace ROWS with RANGE and duplicate dates collapse into one peer group: both rows display 220 and the series appears to skip a step. The grand total in the second column comes from SUM(revenue) OVER (), an empty frame spanning the whole partition, and dividing the running total by it converts any series into a cumulative share without a self-join or a correlated subquery. The planner maintains the aggregate incrementally as it walks the sorted rows, so the running column costs one extra addition per row rather than a second pass over the table.
Running Total by Partition
-- Running total per department (resets per dept)
SELECT
department_id, employee_id, salary,
SUM(salary) OVER (
PARTITION BY department_id
ORDER BY hire_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS dept_running_total,
SUM(salary) OVER (
ORDER BY hire_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS company_running_total
FROM employees
ORDER BY department_id, hire_date;
PARTITION BY rebuilds the frame inside each group. In the query above the department column restarts at the first hire date of every department, while the company-wide column — which declares no partition — keeps climbing across department boundaries, so the two columns disagree by design. Reset points are a modelling decision: partition by department for per-team budgets, add a date function to the partition list for per-month totals, and leave the partition list empty when stakeholders want the company figure. Sort order matters as much as the partition. The frame follows ORDER BY hire_date, not physical insertion order, so re-imported rows carrying earlier dates silently renumber the entire series and change every historical total downstream.
Cumulative Percentage
-- Calculate cumulative percentage of total
SELECT
department_id, employee_id, salary,
SUM(salary) OVER w AS running_total,
SUM(salary) OVER () AS grand_total,
ROUND(SUM(salary) OVER w * 100.0 / SUM(salary) OVER (), 2) AS cumulative_pct
FROM employees
WINDOW w AS (
ORDER BY salary DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
ORDER BY salary DESC;
Cumulative percentage has two moving parts: the numerator is the framed sum and the denominator is the unframed SUM(salary) OVER (). Ordering by salary DESC produces a Pareto curve — the share of total payroll held by the top earners — which is where an 80/20 claim is actually measured instead of asserted. ROUND(..., 2) keeps the output printable, but round only at the end: rounding each row to two decimals before dividing introduces drift that shows up as a final value of 99.97 percent. Because WINDOW w AS (...) names the frame once, every column in the statement reuses the same definition and the numerator and denominator cannot drift apart between them.
Running Average (Moving Averages)
-- Moving averages with different windows
SELECT
sale_date, revenue,
AVG(revenue) OVER (ORDER BY sale_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma_7day,
AVG(revenue) OVER (ORDER BY sale_date ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) AS ma_30day,
AVG(revenue) OVER (ORDER BY sale_date ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING) AS ma_centered_7day
FROM daily_sales
ORDER BY sale_date;
Pick the window from the question, not from habit. ROWS BETWEEN 6 PRECEDING AND CURRENT ROW covers seven physical rows and is the correct seven-day simple moving average on a complete daily series. The first six rows of such a window are warm-up periods computed on partial data, so dashboards either suppress them or publish a separate row-count column alongside the average. ROWS BETWEEN 3 PRECEDING AND 3 FOLLOWING is a centred window: it looks four rows ahead, which is fine for offline smoothing but leaks future data into a live alert. On irregular series, count the frame with COUNT(*) OVER w and treat any window shorter than the declared width as incomplete rather than as a real reading.
Cumulative Sum with Reset at Boundaries
-- Running total that resets at month boundaries
SELECT
department_id, employee_id, salary, hire_date,
SUM(salary) OVER (
PARTITION BY department_id
ORDER BY hire_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS dept_running_total,
-- Reset at month boundaries
SUM(salary) OVER (
PARTITION BY department_id, DATE_TRUNC('month', hire_date)
ORDER BY hire_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS monthly_running_total
FROM employees
ORDER BY department_id, hire_date;
⚠️
Common Mistake: Using RANGE instead of ROWS in the frame clause can produce unexpected results when there are ties in the ORDER BY column. ROWS is generally safer for running totals — it always includes exactly the specified number of physical rows.
Running Maximum and Minimum
-- Running min/max with window functions
SELECT
sale_date, revenue,
MAX(revenue) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_max,
MIN(revenue) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_min,
revenue - MIN(revenue) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS above_running_min,
MAX(revenue) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) - revenue AS below_running_max
FROM daily_sales
ORDER BY sale_date;
Running extremes answer a different question from running sums: where does the current value sit relative to the best and worst seen so far? revenue - MIN(revenue) OVER (...) measures distance above the running floor — the same expression equity curves use for drawdown — and MAX(...) - revenue measures distance below the running peak. Both are monotone by construction: the floor only falls and the ceiling only rises, so a zero in the first column marks a new all-time low for the series and a zero in the second marks a new high. These are the cheapest trend indicators available, one sort plus one frame, and they need no self-join, no correlated subquery and no application-side loop over the result set.
Cumulative Distribution Function
-- CDF and percentile rank calculations
SELECT
employee_id, salary,
CUME_DIST() OVER (ORDER BY salary) AS cumulative_distribution,
PERCENT_RANK() OVER (ORDER BY salary) AS percentile_rank,
NTILE(100) OVER (ORDER BY salary) AS percentile_bucket
FROM employees
ORDER BY salary;
CUME_DIST() returns the fraction of rows at or below the current value — the rank of the last peer divided by the row count — so ties all receive the higher figure. PERCENT_RANK() uses the rank of the first peer minus one, divided by row count minus one, and always starts at exactly 0. On ten salaries where two rows tie for third place, CUME_DIST() reports 0.40 for both rows while PERCENT_RANK() reports 0.22 for both. Neither one interpolates: if you need a value that exists in the data, use these; if you need the salary halfway between two observations, use PERCENTILE_CONT instead. NTILE(100) buckets rows into roughly equal groups for percentile reports, and stays uneven whenever the row count does not divide cleanly by 100.
Running Total with Gaps
-- Handle gaps in data with running total
WITH date_series AS (
SELECT generate_series(
MIN(sale_date), MAX(sale_date), '1 day'::INTERVAL
)::DATE AS date
FROM daily_sales
)
SELECT
ds.date,
COALESCE(s.revenue, 0) AS revenue,
SUM(COALESCE(s.revenue, 0)) OVER (
ORDER BY ds.date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM date_series ds
LEFT JOIN daily_sales s ON ds.date = s.sale_date
ORDER BY ds.date;
Gap filling is the most common production variant of a running total, because business series rarely arrive complete. The pattern has three steps: generate the full calendar with generate_series, left join the sparse facts onto it, then replace the missing values with zero before the frame runs. Coalescing before the window matters — a NULL left inside the frame propagates through SUM and blanks the running total from that row onward, which looks like a data outage rather than a query bug. The same shape handles trading days, billing periods and session timelines; only the generate_series arguments change. For monthly grain, swap the day interval for INTERVAL '1 month' and truncate both sides to the month start before joining.
Quiz: Test Your Knowledge
Follow-Up Questions
- What's the difference between
ROWSandRANGEin running total calculations? - How would you calculate a running total that handles NULL values?
- Explain how to compute a running geometric mean.
- How do you reset running totals at specific intervals?
- What's the best approach for running totals in partitioned tables?
Common Mistakes
Omitting the frame clause and assuming the default frame walks row by row
Fix: Write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW explicitly whenever ties in the ORDER BY column must not be absorbed
Rounding each row before dividing the running total by the grand total
Fix: Keep full precision through the division and round once at the end so the cumulative column reaches 100 percent
Running gap-fill joins after the window so NULLs enter the frame
Fix: Generate the complete calendar, left join the facts, and coalesce to zero before any window aggregate is computed
Relying on insertion order for a date-based running total
Fix: Order the frame by the business date and treat re-imported rows as a renumbering of the whole series
Key Takeaways
- Always specify ROWS —
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWfor true running totals - PARTITION BY resets — running total starts fresh at each partition boundary
- Moving average —
ROWS BETWEEN 6 PRECEDING AND CURRENT ROWfor 7-day MA - Cumulative % — running total / grand total × 100
- CUME_DIST() — returns the proportion of values ≤ current value
- RANGE vs ROWS — RANGE includes ties; ROWS is exact row count