0
0
SQLquery~3 mins

Why Running total without window functions in SQL? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could get running totals instantly without fancy functions or manual math?

The Scenario

Imagine you have a list of daily sales in a spreadsheet, and you want to find the total sales up to each day. Doing this by hand means adding each day’s sales to all the previous days’ totals manually.

The Problem

Manually adding numbers for each day is slow and easy to mess up. If you have many days, it becomes a big headache and mistakes happen often.

The Solution

Using a running total query without window functions lets the database add up values step-by-step automatically. This saves time and avoids errors by letting the computer do the repetitive adding for you.

Before vs After
Before
SELECT day, sales, (SELECT SUM(sales) FROM sales_table WHERE day <= s.day) AS running_total FROM sales_table s;
After
SELECT day, sales, @total := @total + sales AS running_total FROM sales_table, (SELECT @total := 0) t ORDER BY day;
What It Enables

This lets you quickly see cumulative totals in reports or dashboards without complex tools.

Real Life Example

A store manager can track total sales up to each day to understand trends and make better stock decisions.

Key Takeaways

Manual adding is slow and error-prone.

Running totals automate cumulative sums step-by-step.

Databases can do this even without special window functions.