Memra

Running totals and LAG

Frames, cumulative sums, and the previous row.

Cumulative and relative

Add ORDER BY to a windowed SUM and it becomes a running total — each row sums itself and all prior rows in the window:

SELECT ordered_at, id,
       SUM(1) OVER (ORDER BY ordered_at, id) AS orders_so_far
FROM orders;

LAG(col) peeks at the previous row's value (and LEAD the next) — perfect for deltas, e.g. days since the prior order. LAG returns NULL on the first row, since there's nothing before it.

NORMAL ~/memra/learn/postgresql/running-totals utf-8 LF