Running Total in SQL (Beginner-Friendly Step by Step)

One of the most useful and beginner-friendly SQL window function problems is calculating a
πŸ‘‰ Running Total (Cumulative Sum).

If you understand this, you unlock analytics, finance, and reporting queries.

Let’s learn it slowly and clearly πŸ‘‡


🧠 What is a Running Total?

A running total means:

Add the current value to all previous values.

Example numbers:

100 β†’ 150 β†’ 200

Running total:

100 β†’ 250 β†’ 450

πŸ“Š Sample Data

day amount
Day 1 100
Day 2 150
Day 3 200

❌ Wrong Way (Beginner Mistake)

SELECT SUM(amount)
FROM sales;

This gives:

450

❌ You lose row-level details
❌ Not a running total


βœ… Correct Way: Use a Window Function

Step 1: Use SUM() as a window function

SELECT
  day,
  amount,
  SUM(amount) OVER (
    ORDER BY day
  ) AS running_total
FROM sales;

πŸ” How SQL Thinks (Very Important)

  1. Sort rows by day
  2. Start adding amounts from the first row
  3. Keep adding as rows increase

βœ… Final Output

day amount running_total
Day 1 100 100
Day 2 150 250
Day 3 200 450

βœ” Each row keeps its value
βœ” Total keeps growing


🧠 Key Keywords Explained Simply

ORDER BY

πŸ‘‰ Tells SQL which order to add values

OVER()

πŸ‘‰ Tells SQL don’t collapse rows


πŸ“Œ Running Total Per Group (Very Common)

Example:

Running total per product

SELECT
  product,
  sale_date,
  amount,
  SUM(amount) OVER (
    PARTITION BY product
    ORDER BY sale_date
  ) AS running_total
FROM sales;

βœ” Restarts total for each product


🎯 Where Running Totals Are Used

  • Bank balance over time
  • Daily revenue tracking
  • Monthly sales growth
  • Inventory movement
  • Expense accumulation

Simple Rule to Remember 🧠

SUM() + OVER() + ORDER BY = Running Total


πŸ’¬ Interview Question for You

How would you calculate a running total that resets every month?

(Hint: PARTITION BY month πŸ˜‰)