Window Functions · Lesson 60 of 64

SQL Running Totals

What you will learn

  • How SUM(...) OVER (ORDER BY ...) gives a running total
  • How to run a total per group
  • Why ties can surprise you with the default frame
  • How an explicit ROWS frame fixes it

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Run the cells from top to bottom.

1. A running total

When OVER has an ORDER BY, an aggregate becomes cumulative: for each row it covers all rows up to and including this one. Build a monthly series first, then add up as you go:

WITH monthly AS (
    SELECT SUBSTR(order_date, 1, 7) AS month, COUNT(*) AS orders
    FROM orders GROUP BY SUBSTR(order_date, 1, 7)
)
SELECT month, orders,
       SUM(orders) OVER (ORDER BY month) AS orders_so_far
FROM monthly
ORDER BY month
LIMIT 6;
month    orders  orders_so_far
-------  ------  -------------
2024-01      17             17
2024-02      18             35
2024-03      27             62
2024-04      24             86
2024-05      43            129
2024-06      40            169
(6 rows)
WITH monthly AS (
    SELECT SUBSTR(txn_date, 1, 7) AS month, SUM(amount_cents) AS cents
    FROM transactions WHERE kind = 'deposit' GROUP BY SUBSTR(txn_date, 1, 7)
)
SELECT month, cents,
       SUM(cents) OVER (ORDER BY month) AS deposited_so_far
FROM monthly
ORDER BY month
LIMIT 6;
month     cents  deposited_so_far
-------  ------  ----------------
2018-02  108000            108000
2018-03   76000            184000
2018-04  117800            301800
2018-05   91200            393000
2018-06  174700            567700
2018-07  101200            668900
(6 rows)
WITH monthly AS (
    SELECT SUBSTR(enrolled_on, 1, 7) AS month, COUNT(*) AS enrollments
    FROM enrollments GROUP BY SUBSTR(enrolled_on, 1, 7)
)
SELECT month, enrollments,
       SUM(enrollments) OVER (ORDER BY month) AS enrolled_so_far
FROM monthly
ORDER BY month
LIMIT 6;
month    enrollments  enrolled_so_far
-------  -----------  ---------------
2025-01          354              354
2025-02           45              399
2025-07           33              432
2025-08          282              714
2026-01          271              985
2026-02           17             1002
(6 rows)

Each row shows its month and the total up to that month. The last row of the full series equals the grand total, a nice check.

2. A running total per group

Add PARTITION BY and each group starts from zero again:

WITH monthly AS (
    SELECT status, SUBSTR(order_date, 1, 7) AS month, COUNT(*) AS orders
    FROM orders GROUP BY status, SUBSTR(order_date, 1, 7)
)
SELECT status, month, orders,
       SUM(orders) OVER (PARTITION BY status ORDER BY month) AS status_so_far
FROM monthly
WHERE status = 'paid'
ORDER BY month
LIMIT 5;
status  month    orders  status_so_far
------  -------  ------  -------------
paid    2024-01       1              1
paid    2024-02       2              3
paid    2024-03       3              6
paid    2024-04       2              8
paid    2024-05       2             10
(5 rows)
WITH monthly AS (
    SELECT account_id, SUBSTR(txn_date, 1, 7) AS month, SUM(amount_cents) AS cents
    FROM transactions WHERE account_id <= 3 GROUP BY account_id, SUBSTR(txn_date, 1, 7)
)
SELECT account_id, month, cents,
       SUM(cents) OVER (PARTITION BY account_id ORDER BY month) AS account_so_far
FROM monthly
ORDER BY account_id, month
LIMIT 6;
account_id  month     cents  account_so_far
----------  -------  ------  --------------
         1  2025-05  100800          100800
         1  2025-06   19300          120100
         1  2025-07   23800          143900
         1  2025-08   24500          168400
         1  2025-09   57800          226200
         1  2025-10    4300          230500
(6 rows)
WITH monthly AS (
    SELECT section_id, SUBSTR(class_date, 1, 7) AS month, COUNT(*) AS absences
    FROM attendance WHERE status = 'absent' AND section_id <= 3 GROUP BY section_id, SUBSTR(class_date, 1, 7)
)
SELECT section_id, month, absences,
       SUM(absences) OVER (PARTITION BY section_id ORDER BY month) AS section_so_far
FROM monthly
ORDER BY section_id, month
LIMIT 6;
section_id  month    absences  section_so_far
----------  -------  --------  --------------
         1  2025-08         1               1
         1  2025-09         3               4
         2  2025-02         4               4
         2  2025-03         5               9
         3  2025-08         1               1
         3  2025-09         2               3
(6 rows)

3. Running count and running maximum

Any aggregate can run: COUNT, MAX, MIN, AVG:

SELECT product_id, price,
       MAX(price) OVER (ORDER BY product_id) AS highest_so_far
FROM products
ORDER BY product_id
LIMIT 6;
product_id  price  highest_so_far
----------  -----  --------------
         1    6.6             6.6
         2   44.1            44.1
         3   29.5            44.1
         4    5.4            44.1
         5   26.4            44.1
         6   79.0            79.0
(6 rows)
SELECT account_id, balance_cents,
       MAX(balance_cents) OVER (ORDER BY account_id) AS highest_so_far
FROM accounts
ORDER BY account_id
LIMIT 6;
account_id  balance_cents  highest_so_far
----------  -------------  --------------
         1         192400          192400
         2          52078          192400
         3          62780          192400
         4          99900          192400
         5         153100          192400
         6         218400          218400
(6 rows)
SELECT course_id, credits,
       MAX(credits) OVER (ORDER BY course_id) AS highest_so_far
FROM courses
ORDER BY course_id
LIMIT 6;
course_id  credits  highest_so_far
---------  -------  --------------
        1        4               4
        2        3               4
        3        4               4
        4        4               4
        5        4               4
        6        4               4
(6 rows)

4. The tie trap

The default frame (according to the SQLite documentation) with an ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. With RANGE, rows that tie on the ORDER BY value are treated as one: they all show the same running total, which includes all of the tied rows:

CREATE TABLE lib_sales (day TEXT, amount INTEGER);
INSERT INTO lib_sales VALUES ('Mon', 10), ('Tue', 20), ('Tue', 5), ('Wed', 7);
SELECT day, amount,
       SUM(amount) OVER (ORDER BY day) AS default_total
FROM lib_sales ORDER BY day, amount;
day  amount  default_total
---  ------  -------------
Mon      10             10
Tue       5             35
Tue      20             35
Wed       7             42
(4 rows)
CREATE TABLE lib_sales (day TEXT, amount INTEGER);
INSERT INTO lib_sales VALUES ('Mon', 10), ('Tue', 20), ('Tue', 5), ('Wed', 7);
SELECT day, amount,
       SUM(amount) OVER (ORDER BY day) AS default_total
FROM lib_sales ORDER BY day, amount;
day  amount  default_total
---  ------  -------------
Mon      10             10
Tue       5             35
Tue      20             35
Wed       7             42
(4 rows)
CREATE TABLE lib_sales (day TEXT, amount INTEGER);
INSERT INTO lib_sales VALUES ('Mon', 10), ('Tue', 20), ('Tue', 5), ('Wed', 7);
SELECT day, amount,
       SUM(amount) OVER (ORDER BY day) AS default_total
FROM lib_sales ORDER BY day, amount;
day  amount  default_total
---  ------  -------------
Mon      10             10
Tue       5             35
Tue      20             35
Wed       7             42
(4 rows)

Both Tuesday rows show 35 (10 + 20 + 5). That is rarely what you meant by "so far". Make the frame explicit, and add a tie-breaker, to count row by row:

SELECT day, amount,
       SUM(amount) OVER (ORDER BY day, amount ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS row_by_row_total
FROM lib_sales ORDER BY day, amount;
day  amount  row_by_row_total
---  ------  ----------------
Mon      10                10
Tue       5                15
Tue      20                35
Wed       7                42
(4 rows)
SELECT day, amount,
       SUM(amount) OVER (ORDER BY day, amount ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS row_by_row_total
FROM lib_sales ORDER BY day, amount;
day  amount  row_by_row_total
---  ------  ----------------
Mon      10                10
Tue       5                15
Tue      20                35
Wed       7                42
(4 rows)
SELECT day, amount,
       SUM(amount) OVER (ORDER BY day, amount ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS row_by_row_total
FROM lib_sales ORDER BY day, amount;
day  amount  row_by_row_total
---  ------  ----------------
Mon      10                10
Tue       5                15
Tue      20                35
Wed       7                42
(4 rows)

ROWS counts physical rows, so the Tuesday rows now show 15 and 35.

5. Share of the running total

A running total divided by the grand total is a cumulative percentage, handy for finding "the top rows that make up 50%":

SELECT name, stock,
       ROUND(100.0 * SUM(stock) OVER (ORDER BY stock DESC, product_id) / SUM(stock) OVER (), 1) AS cumulative_percent
FROM products
ORDER BY stock DESC, product_id
LIMIT 5;
name            stock  cumulative_percent
--------------  -----  ------------------
Ceramic mug       150                 6.1
Watering can      150                12.2
Plant pot         150                18.2
Seed tray         150                24.3
Pruning shears    150                30.4
(5 rows)
SELECT account_id, balance_cents,
       ROUND(100.0 * SUM(balance_cents) OVER (ORDER BY balance_cents DESC, account_id) / SUM(balance_cents) OVER (), 2) AS cumulative_percent
FROM accounts
ORDER BY balance_cents DESC, account_id
LIMIT 5;
account_id  balance_cents  cumulative_percent
----------  -------------  ------------------
       398         502080                0.81
       243         432800                 1.5
       165         428004                2.19
       238         401600                2.84
       295         379900                3.45
(5 rows)
SELECT section_id, capacity,
       ROUND(100.0 * SUM(capacity) OVER (ORDER BY capacity DESC, section_id) / SUM(capacity) OVER (), 1) AS cumulative_percent
FROM sections
ORDER BY capacity DESC, section_id
LIMIT 5;
section_id  capacity  cumulative_percent
----------  --------  ------------------
         6        35                 2.9
        12        35                 5.8
        13        35                 8.7
        20        35                11.6
        22        35                14.5
(5 rows)

Worked example: a bank statement

Step Do
1 one account's transactions, in order of date and id
2 SUM(signed_amount) OVER (ORDER BY txn_date, txn_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
3 the result is the balance after each transaction
4 compare with a stored balance_after column to find errors

The Bank sample stores balance_after for this reason. The numbers are made up.

Common mistakes

  • No ORDER BY inside OVER, giving the same total on every row.
  • Ties with the default frame, which count tied rows together.
  • No tie-breaker in the ordering.
  • Running a total over rows that were meant to be filtered (remember that WHERE runs first).

Key takeaways

  • SUM(x) OVER (ORDER BY ...) is a running total; add PARTITION BY for one per group.
  • The default frame treats tied rows as a group; write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW with a tie-breaker for row-by-row totals.
  • Divide a running total by the grand total for a cumulative percentage.
  • Any aggregate can run, not just SUM.

Practice

1. Write the window for a running total of amount by day.

Show answer

SUM(amount) OVER (ORDER BY day)

2. How do you restart the total for each account?

Show answer

Add PARTITION BY account_id inside OVER.

3. What happens with the default frame when two rows tie on the ORDER BY value?

Show answer

They both show the same running total, which includes all the tied rows.

4. How do you make the total count row by row?

Show answer

Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW and a tie-breaker in the order.

5. What does the last row of a running total equal?

Show answer

The grand total of the series.

6. How do you get a cumulative percentage?

Show answer

Divide the running total by SUM(x) OVER (), the grand total, and multiply by 100.0.