DELAPARRA
Index
Color
NL
Category: SQL

running total

Explained by Updated

What is running total?

running total: A cumulative sum computed with a window frame — SUM(...) OVER with rows from the start up to the current row. A running total adds up values row by row, so each row shows the sum so far. Daily revenue with a cumulative month-to-date figure next to it is a typical example.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about running total

How is running total used in practice?

In SQL you calculate it with a window function: SUM(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). Add PARTITION BY to restart the total per month or per customer.

What should you keep in mind with running total?

Before window functions, this needed slow self-joins or a loop in application code. Now one query handles it efficiently. Specify ROWS explicitly; the default frame, RANGE, treats rows with the same value in the ordering column as one group, which gives surprising totals when several rows share a date. MySQL 8, PostgreSQL and SQLite all support this.

What does an example of running total look like?

SELECT day, amount, SUM(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running FROM ledger;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with R

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.