Running Total With SUM() OVER
Build a cumulative salary total across employees ordered by hire date.
Overview
A running total accumulates a value as you move down the ordered window. Using
SUM(salary) OVER (ORDER BY hire_date) with a frame that grows row by row gives
the cumulative payroll to date, a classic finance/reporting pattern.
The Query
Loading playground environment...
Step-by-Step Breakdown
SUM(salary) OVER (ORDER BY hire_date): by default the frame isROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so it sums from the first row up to the current one.- Each row's
running_payrollincludes all employees hired on or before that row's date. - No
PARTITION BYmeans the running total spans the whole table.
Frame matters
The default frame for ORDER BY windows accumulates to the current row. If
you want a fixed window, specify ROWS BETWEEN … AND … explicitly.
Variations
Running total of units per customer over time:
Loading playground environment...
Common Mistakes
- Forgetting ORDER BY. Without it, the frame is the whole partition and you get the grand total on every row, not a running sum.
- Wrong PARTITION BY. Omitting
PARTITION BY customer_idmerges all customers into one running total. - Assuming reset per group. Without
PARTITION BY, the total never resets between entities.
Cite this resource
SQLSimplified. "Running Total With SUM() OVER Example". Available at: https://sqlsimplified.online/examples/running-total