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)
- Sort rows by
day - Start adding amounts from the first row
- 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 π)
Comments (0)
No comments yet. Be the first to share your thoughts!
Leave a Comment