Home / SQL / Reference / Window functions

SQL Running totals

Add up values row by row, in order.

Syntax

SUM(x) OVER (ORDER BY …)

Example

Query (on the shop database used in the SQL course)

WITH m AS (
  SELECT strftime('%Y-%m', order_date) AS month, COUNT(*) AS orders
  FROM orders GROUP BY month
)
SELECT month, orders, SUM(orders) OVER (ORDER BY month) AS running_total
FROM m;

Result

monthordersrunning_total
2025-0122
2025-0235
2025-03813
2025-04518
2025-05523
2025-06225
2025-07530
2025-08636
2025-09238
2025-10644
2025-11347
2025-12451

12 rows

Related

Learn it step by step in the free lesson CTEs & Window Functions, with exercises that check your queries.