Running totals, LAG and LEAD
Overview
Time series are everywhere in business data: revenue per month, sign-ups per week, stock per day. The questions are always similar — what’s the total so far?, what’s the trend, smoothed out?, how did this period compare with the last? Window functions with an ordered window answer all of them without self-joins or subqueries.
Running totals
Put ORDER BY inside OVER on an aggregate, and it becomes cumulative — each row’s value covers all rows from the start up to that row:
WITH monthly AS (
SELECT date_trunc('month', ordered_at)::date AS month, count(*) AS orders
FROM orders
GROUP BY 1
)
SELECT month, orders,
sum(orders) OVER (ORDER BY month) AS running_total
FROM monthly
ORDER BY month; month | orders | running_total
------------+--------+---------------
2026-01-01 | 3 | 3
2026-02-01 | 3 | 6
2026-03-01 | 3 | 9
2026-04-01 | 2 | 11
2026-05-01 | 2 | 13
2026-06-01 | 2 | 15
2026-07-01 | 1 | 16
2026-08-01 | 1 | 17
2026-09-01 | 2 | 19
2026-10-01 | 2 | 21
2026-11-01 | 3 | 24
(11 rows)By the end of November, 24 orders in total. Without the ORDER BY inside OVER, every row would show the grand total, 24; with it, each row’s window grows as the months go by.
Window frames
The set of rows an ordered window function looks at for each row is called its frame. You can set it explicitly:
OVER (ORDER BY month ROWS BETWEEN <start> AND <end>)where start and end are things like UNBOUNDED PRECEDING (the first row), 2 PRECEDING (two rows back), CURRENT ROW, 1 FOLLOWING or UNBOUNDED FOLLOWING (the last row).
A moving average smooths out bumps. The average of each month and the two before it:
WITH monthly AS (
SELECT date_trunc('month', ordered_at)::date AS month, count(*) AS orders
FROM orders
GROUP BY 1
)
SELECT month, orders,
round(avg(orders) OVER (ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS moving_avg_3m
FROM monthly
ORDER BY month; month | orders | moving_avg_3m
------------+--------+---------------
2026-01-01 | 3 | 3.00
2026-02-01 | 3 | 3.00
2026-03-01 | 3 | 3.00
2026-04-01 | 2 | 2.67
2026-05-01 | 2 | 2.33
2026-06-01 | 2 | 2.00
2026-07-01 | 1 | 1.67
2026-08-01 | 1 | 1.33
2026-09-01 | 2 | 1.33
2026-10-01 | 2 | 1.67
2026-11-01 | 3 | 2.33
(11 rows)The first two rows average over fewer months because there aren’t two earlier rows yet. A three-month average shows the dip in mid-year more clearly than the raw monthly counts.
ROWS versus RANGE: the tie trap
When you write ORDER BY in a window without a frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE treats rows with the same ORDER BY value — peers — as one step, so they’re all included together. With unique values, like the months above, ROWS and RANGE behave the same. With duplicates, they don’t:
SELECT id, shipping_fee,
sum(shipping_fee) OVER (ORDER BY shipping_fee) AS range_default,
sum(shipping_fee) OVER (ORDER BY shipping_fee, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_frame
FROM orders
WHERE customer_id IN (2, 6)
ORDER BY shipping_fee, id; id | shipping_fee | range_default | rows_frame
----+--------------+---------------+------------
8 | 4.99 | 14.97 | 4.99
15 | 4.99 | 14.97 | 9.98
22 | 4.99 | 14.97 | 14.97
2 | 6.50 | 40.97 | 21.47
7 | 6.50 | 40.97 | 27.97
14 | 6.50 | 40.97 | 34.47
21 | 6.50 | 40.97 | 40.97
(7 rows)Farhan’s three orders all cost 4.99 to ship and Ben’s four all cost 6.50. With the default RANGE frame, tied rows are peers, so all three 4.99 rows show the same total (14.97) — the running total jumps in one step over the whole tie. The ROWS frame, with id added as a tie-breaker so the order is fully defined, adds them one row at a time. For a true row-by-row running total, either order by something unique (add id as a tie-breaker) or say ROWS.
LAG and LEAD: the previous and next row
lag(x) returns the value of x from the previous row in the window order; lead(x) from the next. They’re how you compare each period with the one before:
WITH monthly AS (
SELECT date_trunc('month', ordered_at)::date AS month, count(*) AS orders
FROM orders
GROUP BY 1
)
SELECT month, orders,
lag(orders) OVER (ORDER BY month) AS previous,
lead(orders) OVER (ORDER BY month) AS next,
orders - lag(orders) OVER (ORDER BY month) AS change
FROM monthly
ORDER BY month; month | orders | previous | next | change
------------+--------+----------+------+--------
2026-01-01 | 3 | | 3 |
2026-02-01 | 3 | 3 | 3 | 0
2026-03-01 | 3 | 3 | 2 | 0
2026-04-01 | 2 | 3 | 2 | -1
2026-05-01 | 2 | 2 | 2 | 0
2026-06-01 | 2 | 2 | 1 | 0
2026-07-01 | 1 | 2 | 1 | -1
2026-08-01 | 1 | 1 | 2 | 0
2026-09-01 | 2 | 1 | 2 | 1
2026-10-01 | 2 | 2 | 3 | 0
2026-11-01 | 3 | 2 | | 1
(11 rows)At the edges there’s no previous or next row, so the result is NULL. Both functions take optional extra arguments: an offset (lag(orders, 12) reaches back twelve rows — a year, for monthly data) and a default for the edges (lag(orders, 1, 0)).
Growth rates
Revenue is more interesting than order counts. Month-over-month revenue and its percentage change:
WITH monthly AS (
SELECT date_trunc('month', o.ordered_at)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY 1
)
SELECT month, revenue,
lag(revenue) OVER (ORDER BY month) AS prev_revenue,
round(100 * (revenue - lag(revenue) OVER (ORDER BY month))
/ lag(revenue) OVER (ORDER BY month), 1) AS pct_change
FROM monthly
ORDER BY month; month | revenue | prev_revenue | pct_change
------------+---------+--------------+------------
2026-01-01 | 169.50 | |
2026-02-01 | 117.75 | 169.50 | -30.5
2026-03-01 | 145.65 | 117.75 | 23.7
2026-04-01 | 100.25 | 145.65 | -31.2
2026-05-01 | 120.00 | 100.25 | 19.7
2026-06-01 | 27.25 | 120.00 | -77.3
2026-07-01 | 77.50 | 27.25 | 184.4
2026-08-01 | 40.50 | 77.50 | -47.7
2026-09-01 | 97.40 | 40.50 | 140.5
2026-10-01 | 147.50 | 97.40 | 51.4
2026-11-01 | 102.75 | 147.50 | -30.3
(11 rows)June’s collapse (−77%) and July’s rebound (+184%) show how jumpy a small shop’s numbers are — which is exactly why the moving average above is useful. If a previous month could be zero, wrap the divisor in NULLIF(…, 0).
Per-group sequences with PARTITION BY
Add PARTITION BY and running totals and lag/lead restart for each group. How many days passed between each of a customer’s orders?
SELECT customer_id, id AS order_id, ordered_at::date AS day,
ordered_at::date - lag(ordered_at::date) OVER w AS days_since_last,
count(*) OVER (w ROWS UNBOUNDED PRECEDING) AS order_number
FROM orders
WHERE customer_id IN (1, 2)
WINDOW w AS (PARTITION BY customer_id ORDER BY ordered_at)
ORDER BY customer_id, ordered_at; customer_id | order_id | day | days_since_last | order_number
-------------+----------+------------+-----------------+--------------
1 | 1 | 2026-01-05 | | 1
1 | 3 | 2026-01-28 | 23 | 2
1 | 9 | 2026-03-21 | 52 | 3
1 | 17 | 2026-08-12 | 144 | 4
1 | 23 | 2026-11-20 | 100 | 5
2 | 2 | 2026-01-12 | | 1
2 | 7 | 2026-03-02 | 49 | 2
2 | 14 | 2026-06-07 | 97 | 3
2 | 21 | 2026-10-27 | 142 | 4
(9 rows)Each customer’s first order has no previous order, so days_since_last is NULL, and order_number restarts at 1. Gaps between orders like this feed directly into churn and re-order analysis.
first_value and last_value
first_value(x) and last_value(x) return x from the first or last row of the frame. first_value works as you’d expect; last_value has a surprise — with the default frame ending at the current row, the “last” row is the current one. Extend the frame to see the true last row:
SELECT customer_id, id AS order_id, ordered_at::date AS day,
first_value(id) OVER w AS first_order,
last_value(id) OVER w AS last_order_default,
last_value(id) OVER (w ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_order
FROM orders
WHERE customer_id = 1
WINDOW w AS (PARTITION BY customer_id ORDER BY ordered_at)
ORDER BY ordered_at; customer_id | order_id | day | first_order | last_order_default | last_order
-------------+----------+------------+-------------+--------------------+------------
1 | 1 | 2026-01-05 | 1 | 1 | 23
1 | 3 | 2026-01-28 | 1 | 3 | 23
1 | 9 | 2026-03-21 | 1 | 9 | 23
1 | 17 | 2026-08-12 | 1 | 17 | 23
1 | 23 | 2026-11-20 | 1 | 23 | 23
(5 rows)Tip: when a window result looks wrong, check three things in order: the
PARTITION BY(which rows belong together), theORDER BYinsideOVER(and whether it has ties), and the frame (which rows around the current one are included).
Revenue month by month
Build a monthly revenue report. In a CTE, calculate each month's revenue (sum of quantity × unit price) from orders that weren't cancelled, with month as date_trunc('month', ordered_at)::date. Then return month, revenue, a running_total of revenue up to and including that month, and change — the difference from the previous month's revenue (NULL for the first month). Sort by month.
WITH monthly AS (
SELECT date_trunc('month', o.ordered_at)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY 1
)
SELECT month, revenue
FROM monthly
ORDER BY month;WITH monthly AS (
SELECT date_trunc('month', o.ordered_at)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY 1
)
SELECT month,
revenue,
sum(revenue) OVER (ORDER BY month) AS running_total,
revenue - lag(revenue) OVER (ORDER BY month) AS change
FROM monthly
ORDER BY month;Summary
- With ORDER BY inside OVER, aggregates become cumulative: sum(x) OVER (ORDER BY date) is a running total.
- The frame clause chooses which rows count: ROWS BETWEEN 2 PRECEDING AND CURRENT ROW gives a 3-row moving window.
- The default frame with ORDER BY is RANGE … CURRENT ROW, which includes tied rows; use ROWS when the order column has duplicates.
- lag(x) returns x from the previous row and lead(x) from the next; both return NULL (or a default you give) at the edges.
- Add PARTITION BY to restart running totals and lag/lead for each group, such as each customer.