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_daydaunew_usersreturning_users
2024-04-0112401801060
2024-04-0213152051110
2024-04-0312881641124
2024-04-0413922211171
Watch the cumulative frame grow one day at a timeStep 1 of 4
SUM(new_users) ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
date_daynew_userscumulative_new_users
2024-04-01180180
2024-04-02205385
2024-04-03164549
2024-04-04221770

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.

Advanced business practice

Sign up free to try it on a real business scenario