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
| month | orders | running_total |
|---|---|---|
| 2025-01 | 2 | 2 |
| 2025-02 | 3 | 5 |
| 2025-03 | 8 | 13 |
| 2025-04 | 5 | 18 |
| 2025-05 | 5 | 23 |
| 2025-06 | 2 | 25 |
| 2025-07 | 5 | 30 |
| 2025-08 | 6 | 36 |
| 2025-09 | 2 | 38 |
| 2025-10 | 6 | 44 |
| 2025-11 | 3 | 47 |
| 2025-12 | 4 | 51 |
12 rows
Related
Learn it step by step in the free lesson CTEs & Window Functions, with exercises that check your queries.