SQL Running Total
The most common applied pattern in this entire series — watch a number accumulate as you read down the results.
What & Why
A running total is a windowed sum whose frame begins at the partition start and ends at the current row. Cumulative totals track progress toward a target while preserving each date in the output.
See How It Works
BUSINESS QUESTION
Track cumulative new users across the daily active-user table.
| date_day | dau | new_users | returning_users |
|---|---|---|---|
| 2024-04-01 | 1240 | 180 | 1060 |
| 2024-04-02 | 1315 | 205 | 1110 |
| 2024-04-03 | 1288 | 164 | 1124 |
| 2024-04-04 | 1392 | 221 | 1171 |
Watch the cumulative frame grow one day at a timeStep 1 of 4
SUM(new_users) ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
| date_day | new_users | cumulative_new_users |
|---|---|---|
| 2024-04-01 | 180 | 180 |
| 2024-04-02 | 205 | 385 |
| 2024-04-03 | 164 | 549 |
| 2024-04-04 | 221 | 770 |
The opening frame contains only April 1.
EXAMPLE QUERY
SELECT
date_day,
new_users,
SUM(new_users) OVER (
ORDER BY date_day
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS cumulative_new_users
FROM growth.daily_active_users
ORDER BY date_day;This lesson's practice is part of Pro.
Sign up free to try it on a real business scenario