🗄️ SQL examples

Running Total Examples in SQL

Calculate cumulative totals over time. This page gives you the syntax, five practical examples, common mistakes, and copy-ready SQL you can adapt.

Updated 2026-06-125 practical examplesCopy-ready SQL

💡 Ideas for You

Learning resources for SQL queries, databases and reporting workflows.

4 useful links

Some links in this section may be affiliate links. Choose only what is useful for your own work.

What Running Total does

Calculate cumulative totals over time. SQL syntax can vary by database, but the pattern below is a useful starting point for reports and analysis.

Syntax or pattern

SUM(amount) OVER (ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
✍️

5 practical examples

1

Running sales by date

Create cumulative sales over time.

SELECT order_date, amount, SUM(amount) OVER (ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_sales FROM daily_sales;

A running total accumulates each row with all prior rows.

2

Running total by customer

Restart cumulative amount for each customer.

SELECT customer_id, order_date, total_amount, SUM(total_amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS customer_running_total FROM orders;

PARTITION BY restarts the running total per customer.

3

Running count of orders

Count orders over time.

SELECT order_date, COUNT(*) OVER (ORDER BY order_date) AS running_order_count FROM orders;

This shows growth in order volume.

4

Running inventory movement

Track stock movement across dates.

SELECT movement_date, quantity_change, SUM(quantity_change) OVER (PARTITION BY product_id ORDER BY movement_date) AS stock_balance FROM inventory_movements;

Useful for inventory history reports.

5

Running total after monthly grouping

Summarize monthly sales, then accumulate.

WITH monthly AS ( SELECT DATE_TRUNC('month', order_date) AS month, SUM(total_amount) AS sales FROM orders GROUP BY 1 ) SELECT month, sales, SUM(sales) OVER (ORDER BY month) AS running_sales FROM monthly;

Group first when the running total should be by month rather than by row.

Common mistakes to avoid

  • Forgetting that SQL dialects vary across PostgreSQL, SQL Server, MySQL, BigQuery and SQLite.
  • Using SELECT * in production reports when only a few columns are needed.
  • Not checking join keys, duplicate rows or NULL values before trusting results.

FAQ

Will this SQL work in every database?

The idea is portable, but function names and date syntax may vary. Check your database dialect if a function is not recognized.

Should I use this in a report query?

Yes, if the pattern matches the business question and you have checked filters, joins and row counts.

Why does my result have too many rows?

The most common reasons are duplicate join keys, missing filters or grouping at the wrong level of detail.