Reading history

Running Totals and Moving Averages in SQL

5 min read 0 views

Calculate running totals and moving averages in SQL with window frames: ROWS BETWEEN, the RANGE default with ties, and totals that restart per group.

A shop owner wants to know total sales so far this month, and a smoother trend line that ignores day-to-day ups and downs. These are a running total and a moving average. In SQL both come from window functions with a frame: a sliding group of rows around the current one. This lesson shows how frames work and the subtle difference between ROWS and RANGE.

In this lesson you will learn

  • Running totals with SUM() OVER (ORDER BY …)
  • Window frames: ROWS BETWEEN … AND …
  • Moving averages over the last N rows
  • Why ROWS and RANGE differ when values tie
  • Running totals that restart for each group

You should know window functions and aggregate functions.

Running Total and 3-Day Moving Average

CREATE TABLE daily (day TEXT, units INTEGER);
INSERT INTO daily VALUES
 ('2026-03-01',12),('2026-03-02',15),('2026-03-03',9),('2026-03-04',20),
 ('2026-03-05',18),('2026-03-06',7),('2026-03-07',22);

SELECT day,
       units,
       SUM(units) OVER (ORDER BY day)                                        AS running_total,
       ROUND(AVG(units) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS avg_3day,
       COUNT(*)  OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS days_in_window
FROM daily;

Output

+------------+-------+---------------+----------+----------------+
| day        | units | running_total | avg_3day | days_in_window |
+------------+-------+---------------+----------+----------------+
| 2026-03-01 | 12    | 12            | 12.0     | 1              |
| 2026-03-02 | 15    | 27            | 13.5     | 2              |
| 2026-03-03 | 9     | 36            | 12.0     | 3              |
| 2026-03-04 | 20    | 56            | 14.67    | 3              |
| 2026-03-05 | 18    | 74            | 15.67    | 3              |
| 2026-03-06 | 7     | 81            | 15.0     | 3              |
| 2026-03-07 | 22    | 103           | 15.67    | 3              |
+------------+-------+---------------+----------+----------------+
(7 rows)
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW (current row: 4 March)Mar 112Mar 215Mar 39Mar 420Mar 518Mar 67Mar 722average of 15, 9, 20 = 14.67running total: UNBOUNDED PRECEDING to CURRENT ROW = 56later rows are not used
  • SUM(units) OVER (ORDER BY day) adds up every row from the first day to the current one: 12, then 12 + 15 = 27, and so on to 103.
  • ROWS BETWEEN 2 PRECEDING AND CURRENT ROW is a frame of at most three rows. On 4 March it averages 15, 9 and 20, giving 14.67.
  • The first two days have fewer rows in their frame, shown by days_in_window. Many reports hide those early values or mark them as incomplete.

Frame Options

FrameMeaning
UNBOUNDED PRECEDINGFrom the first row of the partition
n PRECEDINGn rows before the current row
CURRENT ROWThe current row
n FOLLOWINGn rows after the current row
UNBOUNDED FOLLOWINGTo the last row of the partition

A centred 3-row average uses ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING. A grand total on every row uses ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or simply OVER ().

ROWS vs RANGE

-- ROWS vs RANGE when values tie
CREATE TABLE pay (day INTEGER, amount INTEGER);
INSERT INTO pay VALUES (1,100),(2,50),(2,30),(3,20);

SELECT day, amount,
       SUM(amount) OVER (ORDER BY day ROWS  BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_total,
       SUM(amount) OVER (ORDER BY day RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS range_total
FROM pay;

-- Running total that restarts for each customer
SELECT customer, order_date, amount,
       SUM(amount) OVER (PARTITION BY customer ORDER BY order_date) AS customer_total
FROM orders
WHERE amount IS NOT NULL
ORDER BY customer, order_date;

Output

+-----+--------+------------+-------------+
| day | amount | rows_total | range_total |
+-----+--------+------------+-------------+
| 1   | 100    | 100        | 100         |
| 2   | 50     | 150        | 180         |
| 2   | 30     | 180        | 180         |
| 3   | 20     | 200        | 200         |
+-----+--------+------------+-------------+
(4 rows)

+----------+------------+--------+----------------+
| customer | order_date | amount | customer_total |
+----------+------------+--------+----------------+
| Joya     | 2026-02-14 | 2300   | 2300           |
| Joya     | 2026-03-21 | 300    | 2600           |
| Karim    | 2026-01-05 | 1200   | 1200           |
| Karim    | 2026-02-02 | 800    | 2000           |
| Karim    | 2026-03-09 | 1500   | 3500           |
| Rina     | 2026-01-18 | 450    | 450            |
| Rina     | 2026-02-27 | 650    | 1100           |
+----------+------------+--------+----------------+
(7 rows)
  • When you write only ORDER BY, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
  • RANGE treats rows with the same ORDER BY value as one group. Both day-2 rows show 180, because they include each other.
  • ROWS counts physical rows, so the two day-2 rows get 150 and 180.
  • With PARTITION BY customer, the running total starts again for each customer: Karim’s reaches 3500.

If the order column can have ties, add a tie-breaker such as ORDER BY day, id, or use ROWS, so the running total grows one row at a time.

Common Mistakes

  1. Using GROUP BY for a running total. Grouping collapses rows; window functions keep every row.
  2. Surprised by ties. The default RANGE frame gives tied rows the same running total.
  3. Moving average over missing days. “Last 3 rows” is not “last 3 days” if some days are missing. Fill the calendar first.
  4. Ignoring NULLs. SUM and AVG skip NULL values, so an average may be based on fewer rows than you think.

Practice Exercises

Exercise 1. For delivered orders in date order, show the running total of amount and the average of each order with the one before it.

Show answer
SELECT order_date, amount,
       SUM(amount) OVER (ORDER BY order_date) AS running,
       ROUND(AVG(amount) OVER (ORDER BY order_date
             ROWS BETWEEN 1 PRECEDING AND CURRENT ROW), 1) AS avg2
FROM orders
WHERE status = 'delivered';

The running total ends at 5750; the last two-order average is (1500 + 300) ÷ 2 = 900.

Exercise 2. Show each day’s share of the week’s total units in daily as a percentage.

Show answer
SELECT day, units,
       ROUND(100.0 * units / SUM(units) OVER (), 1) AS pct_of_week
FROM daily;

OVER () sums all 7 rows (103), so 22 units on 7 March is 21.4%.

Frequently Asked Questions

Can I make a moving average over the last 7 days instead of the last 7 rows?

Some databases, such as PostgreSQL and recent SQLite, allow RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW or a numeric range on a day number. Another portable way is to fill missing days with a calendar table first, then use ROWS.

Are running totals slow on big tables?

Window functions compute running totals in one pass over sorted rows, which is much faster than a correlated subquery that re-adds every earlier row. An index on the order column can avoid the sort.

Summary

  • SUM() OVER (ORDER BY …) gives a running total.
  • ROWS BETWEEN n PRECEDING AND CURRENT ROW gives a moving window of n + 1 rows.
  • The default frame uses RANGE, which groups tied values together.
  • PARTITION BY restarts the running total for each group.

Next: Top N Per Group in SQL.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *