runtime
37 / 88

lesson 37 Window functions · advanced

Running totals

Add values progressively in a defined order.

the idea

SUM as a window function keeps each row and accumulates values over a frame. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW means all earlier rows plus this row.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT
  id,
  quantity,
  SUM(quantity) OVER( ORDER BY ordered_at,id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_units
FROM orders;

Watch for: Specify a ROWS frame to avoid a default RANGE frame grouping equal sort values.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Keep every order in order. A running total still returns each order. The frame adds this row to the rows before it.

    step-1.sql
    SELECT id, quantity, ordered_at
    FROM orders
    ORDER BY ordered_at, id;
  2. Run the reference. SUM as a window function keeps each row and accumulates values over a frame. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW means all earlier rows plus this row.

    step-2.sql
    SELECT
      id,
      quantity,
      SUM(quantity) OVER( ORDER BY ordered_at,id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_units
    FROM orders;

challenge 1

Show id, quantity and running_units: cumulative quantity ordered by ordered_at then id.

Return idquantityrunning_unitsany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.