SQL running total
A running total adds up values row by row in order. In SQL it is a SUM window function with an ORDER BY inside OVER.
Add PARTITION BY to restart the running total for each group, for example per customer or per year.
Syntax
SUM(value) OVER (ORDER BY date_col)
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
Examples
1. Cumulative orders
SELECT order_date, COUNT(*) AS orders, SUM(COUNT(*)) OVER (ORDER BY order_date) AS running_total FROM orders WHERE order_date BETWEEN '2025-01-01' AND '2025-01-31' GROUP BY order_date ORDER BY order_date;
Orders per day and the cumulative count in January 2025.
Common mistakes
- Duplicate order values: rows with the same date get the same running total by default (RANGE frame). Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for strict row-by-row totals.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
For January 2025, return each order_date that had orders, the number of orders that day, and a running total of orders, in date order.
FAQ
How do I calculate a moving average?
AVG(value) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) gives a 7-row moving average.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.