Learn SQL
-- windows.running_totals

Running Totals & Moving Averages in SQL

Aggregate over a moving frame of rows

--concept

Aggregate windows like SUM() OVER (…) compute totals across an ordered frame of rows instead of one final number. SUM(salary) OVER (ORDER BY id) produces a running total that grows row by row; adding ROWS BETWEEN 2 PRECEDING AND CURRENT ROW turns it into a 3-row moving average. This is the SQL way to do cumulative and rolling metrics without pulling data into a spreadsheet.

--how it works
1

Define the row sequence

OVER (ORDER BY id) — the frame slides along id order; without ORDER BY the whole partition is one frame and every row sees the same total.

2

Default frame = running

With ORDER BY, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW — everything from the start up to here.

3

Shrink the frame for moving windows

ROWS BETWEEN 2 PRECEDING AND CURRENT ROW — at most three rows: the current one and its two predecessors.

4

The engine streams the frame

One sort, then at each row add the entering row and drop the leaving one — O(n) after the sort, not O(n × frame).

5

Partition restarts the tape

SUM(…) OVER (PARTITION BY department ORDER BY id) — running totals that reset per department.

--visualization
Alice85k……Bob52k……Cynthia91k……David47k……Elena58k……Farid73k……moving_avgrunning_totalSUM(salary) OVER (ORDER BY id) · AVG(salary) OVER (ORDER BY id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
running total (grows forever) 3-row moving frame (slides)
Stage 1 / 7
SUM(salary) OVER (ORDER BY id) needs a frame that grows: UNBOUNDED PRECEDING → CURRENT ROW.
--example
query.sql
1SELECT name, salary,
2 SUM(salary) OVER (ORDER BY id) AS running_total,
3 AVG(salary) OVER (ORDER BY id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg
4FROM employees ORDER BY id;
Result
namesalaryrunning_totalmoving_avg
Alice850008500085000
Bob5200013700068500
Cynthia9100022800076000
David4700027500063333.33
Elena5800033300065333.33
Farid7300040600059333.33

running_total accumulates salaries in id order: 85k, +52k = 137k, +91k = 228k… ending at the 406k payroll. moving_avg averages each row with its two predecessors — by Farid the early big salaries have slid out of the frame, so it dips to 59,333.33.

--variants

Running payroll total

Cumulative SUM in id order.

query.sql
1SELECT name, salary,
2 SUM(salary) OVER (ORDER BY id) AS running_total
3FROM employees ORDER BY id;
Result
namesalaryrunning_total
Alice8500085000
Bob52000137000
Cynthia91000228000
David47000275000
Elena58000333000
Farid73000406000
1Each row adds its salary to everything before it: 85k → 137k → 228k …
2The final row carries the grand total, 406,000 — but every intermediate row shows its prefix sum.
3The same query with COUNT(*) counts hires cumulatively; AVG tracks the running mean.

3-row moving average

The frame limits how far back the aggregate sees.

query.sql
1SELECT name, salary,
2 AVG(salary) OVER (ORDER BY id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg
3FROM employees ORDER BY id;
Result
namesalarymoving_avg
Alice8500085000
Bob5200068500
Cynthia9100076000
David4700063333.33
Elena5800065333.33
Farid7300059333.33
1Alice’s frame holds only herself → 85,000. Bob’s holds two rows → 68,500.
2From Cynthia onward the frame is full: three rows, e.g. (52k+91k+47k)/3 = 63,333.33.
3By Farid the early large salaries have slid out — the average dips to 59,333.33 despite his own high salary.

Running total per department

PARTITION BY restarts the accumulation.

query.sql
1SELECT name, department, salary,
2 SUM(salary) OVER (PARTITION BY department ORDER BY id) AS dept_running
3FROM employees WHERE department IN ('Engineering', 'Sales') ORDER BY department, id;
Result
namedepartmentsalarydept_running
AliceEngineering8500085000
CynthiaEngineering91000176000
FaridEngineering73000249000
BobSales5200052000
ElenaSales58000110000
1Engineering’s tape: 85k → 176k → 249k. Sales restarts: 52k → 110k.
2Each partition sums independently — the department never sees another department’s rows.
3The final values per department are simply that department’s payroll.

ROWS vs RANGE — the duplicate trap

RANGE groups peers; ROWS counts physical rows.

query.sql
1SELECT salary,
2 COUNT(*) OVER (ORDER BY salary ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS rows_frame,
3 COUNT(*) OVER (ORDER BY salary RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) AS range_frame
4FROM employees WHERE department = 'Engineering' ORDER BY salary;
5-- Engineering salaries: 73000, 85000, 91000 (no dupes here; with 85000 twice the two frames diverge)
Result
salaryrows_framerange_frame
7300011
8500022
9100022
1Without duplicate order keys the two frames coincide — the divergence needs peers.
2Add a second 85,000: ROWS counts both physical rows in the frame; RANGE treats them as one peer bound.
3Rule: financial ledgers and per-row math want ROWS; “value-based” windows want RANGE.
--key facts
ROWS vs RANGEROWS counts physical rows; RANGE groups peer values — duplicates shift the result
Frame = performancewide frames cost memory; engines stream narrow ones efficiently
Everyday usescumulative revenue, 7-day moving averages, stock-on-hand burn-down
--use cases
Cumulative revenue, MTD/ YTD charts, burn-down of remaining budget
7-day moving averages that smooth noisy daily metrics
Stock-on-hand ledgers: cumulative in − out per SKU
Detecting trends: current row vs rolling mean (z-score style flags)
--under the hood
Window frames run after the sort — the plan shows Sort → WindowAgg; a matching index can remove the Sort node.
Huge frames are the cost driver; RANGE with big peer groups or wide ROWS windows can spill to disk.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.