🎓 A1Learner
🔍
0 of 51 lessons completed

SQL Running Totals

A running total keeps a sum that grows as each new row joins in. The final row carries the whole sum, and the rows before it show the sum at that point.

The first three orders

Three lines come back, with the running total at 117.98 by 2024-02-02.

SELECT orders.order_id, orders.order_date, ROUND(products.price * orders.quantity, 2) AS line_total, ROUND(SUM(products.price * orders.quantity) OVER (ORDER BY orders.order_date), 2) AS running_total
FROM orders
JOIN products ON orders.product_id = products.product_id
ORDER BY orders.order_date
LIMIT 3;

The whole running total

The total climbs with each order date and lands on 319.2, the revenue of all ten orders together.

SELECT order_date, ROUND(SUM(products.price * orders.quantity) OVER (ORDER BY orders.order_date), 2) AS running_total
FROM orders
JOIN products ON orders.product_id = products.product_id
ORDER BY order_date;

Counting orders as they arrive

The count climbs 1 to 10 in date order, reaching 10 on the last order.

SELECT order_id, order_date, COUNT(*) OVER (ORDER BY order_date) AS order_count
FROM orders
ORDER BY order_date;

Example

SELECT orders.order_id, orders.order_date, products.name AS product, ROUND(products.price * orders.quantity, 2) AS line_total, ROUND(SUM(products.price * orders.quantity) OVER (ORDER BY orders.order_date), 2) AS running_total
FROM orders
JOIN products ON orders.product_id = products.product_id
ORDER BY orders.order_date;

Key points

  • Running total: a sum that grows row by row in a set order
  • SUM with OVER and an ORDER BY inside it builds the running total.
  • The ORDER BY inside OVER fixes the order the rows add up in.
  • Each row's total covers that row and all the rows before it.
  • Money sums can carry extra decimal places, so ROUND trims the running total to two places.
  • An order line's revenue is its product price times its quantity.

In this example, the join brings each order its product price, and price times quantity gives the line total. SUM with OVER adds the line totals in order of order_date, so the running total grows from 39.99 on the first order to 319.2 on the last. The dates are all different, so the order the rows add up in is fixed.

Try it Yourself

Edit the code, then press Run.

Running is simulated · DB Fiddle

Exercise

What does the last row of a running total hold?