🧠 Running Totals with SUM(): Build Values Over Time

Xorthax now understands how to group data, order it, and control which rows are included. Now he wants to answer a very common question:

“How much has happened so far?”

That’s a running total.




🚀 Running Totals with SUM() OVER()

A running total adds values step-by-step as you move through ordered rows.

SUM(column) OVER (
  PARTITION BY column
  ORDER BY column
)

The logic is:

  • PARTITION BY defines the group
  • ORDER BY defines the sequence
  • The calculation builds as you move through the rows



📊 Example: Customer Spending Over Time

🧾 Sample Data

OrderDate CustomerID Amount
2024-01-01A100
2024-01-05A150
2024-01-10A200

SELECT OrderDate, CustomerID, Amount,
       SUM(Amount) OVER (
         PARTITION BY CustomerID
         ORDER BY OrderDate
       ) AS RunningTotal
FROM Orders;

Result:

OrderDate CustomerID Amount RunningTotal
2024-01-01A100100
2024-01-05A150250
2024-01-10A200450

Each row shows the total up to that point in time.




🧠 What’s Happening Here?

ORDER BY OrderDate puts the rows in sequence from earliest to latest.

From the previous lesson, you learned that a window frame controls which rows are included in the calculation.

In this case, we didn’t write a frame—but SQL still uses one by default.

It includes:

  • The current row
  • All rows that came before it

That’s why the total keeps growing as you move down the table.

Later, you’ll learn how to control this more precisely using options like UNBOUNDED PRECEDING.






🧪 Practice What You Just Learned

Running Total by Customer

For each order, calculate a running total of totalamount for each customer, ordered by orderdate.


Tables Used
orders
ColumnType
orderidbigint
customeridbigint
orderdatetimestamp without time zone
totalamountdouble precision
statustext
Expected Output
Column
customerid
orderid
orderdate
totalamount
running_total
Write Your Query:



➡️ Next Step

Running totals use all previous rows.

Next, you’ll learn how to limit the calculation to a smaller window that moves with each row.




Want to go deeper?