SQL Query

PostgreSQL: SQL Query for Running Total

PostgreSQL guide: Calculate cumulative sum using window functions with SUM() OVER().

This guide is specifically for PostgreSQL syntax.

SQL Query for Running Total

Calculate cumulative sum using window functions with SUM() OVER().

Quick Answer

SELECT date, amount, SUM(amount) OVER (ORDER BY date) as running_total FROM transactions;

Explanation

SUM() OVER() creates a running total. ORDER BY defines the accumulation order. PARTITION BY restarts the total for each group.

Query Variants

Basic

SELECT transaction_date, amount, SUM(amount) OVER (ORDER BY transaction_date) as running_total FROM transactions;

Partitioned

SELECT account_id, transaction_date, amount, SUM(amount) OVER (PARTITION BY account_id ORDER BY transaction_date) as account_balance FROM transactions;

Moving Average

SELECT date, value, AVG(value) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) as moving_avg_7 FROM daily_stats;

Pro Tips

  • PARTITION BY creates separate running totals per group
  • Use ROWS BETWEEN for moving windows
  • Available in most modern databases

Related SQL Queries

Continue learning with more SQL query examples:


PostgreSQL-Specific Notes

This page covers PostgreSQL syntax. Other databases may have different syntax for similar operations.

Related Content

From Our Blog

Try it yourself

Practice this query in our interactive SQL sandbox.