0
0
SQLquery~5 mins

Running totals with SUM OVER in SQL

Choose your learning style9 modes available
Introduction
Running totals help you see the sum of values up to each row, like keeping a growing score in a game.
Tracking daily sales totals that add up over time.
Calculating cumulative points in a sports league.
Showing how expenses add up month by month.
Monitoring total steps walked each day in a fitness app.
Syntax
SQL
SELECT column1, column2, SUM(column_to_sum) OVER (ORDER BY column_to_order) AS running_total
FROM table_name;
The OVER clause defines how to calculate the running total by ordering rows.
ORDER BY inside OVER is required to get a running sum in the correct sequence.
Examples
Calculate running total of sales ordered by date.
SQL
SELECT date, sales, SUM(sales) OVER (ORDER BY date) AS running_total
FROM daily_sales;
Running total of points ordered by player ID.
SQL
SELECT id, points, SUM(points) OVER (ORDER BY id) AS cumulative_points
FROM game_scores;
Shows cumulative expenses month by month.
SQL
SELECT month, expense, SUM(expense) OVER (ORDER BY month) AS total_expense
FROM monthly_expenses;
Sample Program
This example creates a sales table with daily amounts and shows the running total of sales by day.
SQL
CREATE TABLE sales (
  day INT,
  amount INT
);

INSERT INTO sales (day, amount) VALUES
(1, 100),
(2, 150),
(3, 200),
(4, 50);

SELECT day, amount, SUM(amount) OVER (ORDER BY day) AS running_total
FROM sales
ORDER BY day;
OutputSuccess
Important Notes
Running totals are very useful for reports that show progress over time.
Make sure to use ORDER BY inside OVER to get correct running sums.
Without ORDER BY, SUM OVER will sum all rows, not a running total.
Summary
Running totals add values up to each row in order.
Use SUM() with OVER(ORDER BY ...) to calculate running totals.
Great for tracking cumulative data like sales or points.