Forgly

SQL to calculate a running total

Compute a cumulative sum that grows row by row.

PostgreSQL, MySQL 8+, SQL Server, SQLite 3.25+
SELECT order_date,
       amount,
       SUM(amount) OVER (
         ORDER BY order_date
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_total
FROM orders
ORDER BY order_date;

How to calculate a running total (cumulative sum)

A running total adds up values up to and including the current row, ordered by a column such as date — a window function does this in one pass.

How it works

  • SUM(amount) OVER (...) is a windowed sum — it does not collapse rows like GROUP BY does.
  • ORDER BY order_date defines the direction the total accumulates.
  • ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW limits the sum to all rows from the start up to the current one.
  • Add PARTITION BY customer_id to keep a separate running total per customer.

Related SQL queries

Frequently asked questions

How do I calculate a running total (cumulative sum) in SQL?

A running total adds up values up to and including the current row, ordered by a column such as date — a window function does this in one pass. SUM(amount) OVER (...) is a windowed sum — it does not collapse rows like GROUP BY does. ORDER BY order_date defines the direction the total accumulates. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW limits the sum to all rows from the start up to the current one. Add PARTITION BY customer_id to keep a separate running total per customer.

Does this work in PostgreSQL, MySQL, SQL Server, and SQLite?

Yes — this query uses standard SQL that runs unchanged on PostgreSQL, MySQL, SQL Server, and SQLite.

Can I generate this query for my own tables?

Yes. Describe what you want in plain English with Forgly's free AI SQL Generator and it writes the query for your dialect.