Running Totals with Window Functions
intermediatewindow-functions
2 min read
What are Running Totals?
A running total (cumulative sum) adds each row's value to the sum of all previous rows. Window functions make this straightforward with SUM() OVER(ORDER BY ...).
Syntax
SELECT column,
SUM(column) OVER (ORDER BY order_column) AS running_total
FROM table_name;When to Use
- Tracking cumulative revenue over time
- Showing account balance progression
- Monitoring cumulative enrollment counts
Key Points
- Default Frame —
SUM() OVER (ORDER BY col)defaults toROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. - PARTITION BY — Add PARTITION BY to restart the running total per group.
- Moving Average — Use
AVG() OVER (ORDER BY col ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)for a 3-row moving average. - Running Count —
COUNT(*) OVER (ORDER BY col)gives a running count. - Performance — Window functions are efficient; the database scans once and accumulates.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
Running Totals with Window Functions Challenge
Write a query that solve this task: show each order with a running total of revenue.
Expected result
Each order with a cumulative_revenue column that grows with each row.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What are Running Totals?
Initializing database...Each run starts from fresh sample data.
More Examples
Running total per student
Cumulative spending per student, ordered by order date.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
How does the window frame affect running totals?
The default frame with ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. For strict row-by-row totals, use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
Can I do a running average?
Yes. Replace SUM with AVG and optionally define a frame: AVG(total) OVER (ORDER BY id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW).