LAG, LEAD and running totals
the previous row, the next row, and a sum of every row so far.
- address
- everything.analytics.lag_and_lead
- part
- part 4, windows, grouping and recursion
- chapter
- chapter 6 of 11
- reading time
- 7 min
lag(x) is the value of x on the row before this one, in the window's order. lead(x) is the row after. both take an offset and a default: lag(x, 2, 0) is two rows back, or 0 if there's no such row.
a running total is sum(x) OVER (ORDER BY ...): the default frame runs from the first row to this one.
the picture
you know how in a spreadsheet you write =B3-B2 and drag it down, and every row compares itself with the row above? SQL rows don't have row numbers you can point at, and a self join on "the previous month" is a mouthful. lag is that B2.
think of a queue where everyone can turn around and read the badge of the person behind them (lag), or tap the shoulder of the person in front (lead). the queue's order is the window's ORDER BY. the first person in line has nobody behind, so they read nothing: NULL.
- 1SELECT month, revenue,
- 2 lag(month) OVER w AS read_from,
- 3 lag(revenue) OVER w AS value
- 4FROM monthly
- 5WINDOW w AS (ORDER BY month)
- 6ORDER BY month;
| month | revenue | value |
|---|---|---|
| 2025-07-01 | 348021.73 | null |
| 2025-08-01 | 360384.79 | 348021.73 |
| 2025-09-01 | 342888.77 | 360384.79 |
| 2025-10-01 | 358400.90 | 342888.77 |
| 2025-11-01 | 354606.47 | 358400.90 |
| 2025-12-01 | 346452.85 | 354606.47 |
| 2026-01-01 | 352732.50 | 346452.85 |
| 2026-02-01 | 331476.19 | 352732.50 |
| 2026-03-01 | 355904.75 | 331476.19 |
| 2026-04-01 | 355887.10 | 355904.75 |
| 2026-05-01 | 353582.15 | 355887.10 |
| 2026-06-01 | 306277.84 | 353582.15 |
month 2025-10-01 reads month 2025-09-01. lag(revenue) reads the row one before in the window's order: last month. july has no row before it, so it gets NULL.
value. the arrow is real: each run also selected lag(month), the month postgres actually read.lag and lead don't care about frames. they count rows in the whole partition, in the window's order, and that's all.
the month before
revenue per month is a view, so the queries stay short (cancelled and refunded orders don't count):
CREATE VIEW monthly AS
SELECT date_trunc('month', o.ordered_at)::date AS month,
sum(oi.qty * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.status NOT IN ('cancelled', 'refunded')
GROUP BY 1;
SELECT month, revenue,
revenue - lag(revenue) OVER w AS change,
round(100 * (revenue / lag(revenue) OVER w - 1), 1) AS pct
FROM monthly
WINDOW w AS (ORDER BY month)
ORDER BY month;| monthdate | revenuenumeric | changenumeric | pctnumeric |
|---|---|---|---|
| 2025-07-01 | 348021.73 | null | null |
| 2025-08-01 | 360384.79 | 12363.06 | 3.6 |
| 2025-09-01 | 342888.77 | -17496.02 | -4.9 |
| 2025-10-01 | 358400.90 | 15512.13 | 4.5 |
| 2025-11-01 | 354606.47 | -3794.43 | -1.1 |
| 2025-12-01 | 346452.85 | -8153.62 | -2.3 |
| 2026-01-01 | 352732.50 | 6279.65 | 1.8 |
| 2026-02-01 | 331476.19 | -21256.31 | -6.0 |
| 2026-03-01 | 355904.75 | 24428.56 | 7.4 |
| 2026-04-01 | 355887.10 | -17.65 | 0.0 |
| 2026-05-01 | 353582.15 | -2304.95 | -0.6 |
| 2026-06-01 | 306277.84 | -47304.31 | -13.4 |
february dropped 6.0% (it's a short month), and june fell off a cliff because the data ends partway through it. july's change is NULL: nothing to compare with, and anything minus NULL is NULL (three-valued logic again).
the third argument replaces that NULL. it's only used when the row doesn't exist, never when it exists and holds a NULL:
SELECT month,
lag(revenue, 1, 0) OVER (ORDER BY month) AS prev_or_zero,
lead(month) OVER (ORDER BY month) AS next_month
FROM monthly
ORDER BY month
LIMIT 3;| monthdate | prev_or_zeronumeric | next_monthdate |
|---|---|---|
| 2025-07-01 | 0 | 2025-08-01 |
| 2025-08-01 | 348021.73 | 2025-09-01 |
| 2025-09-01 | 360384.79 | 2025-10-01 |
a sum of every row so far
swap lag for an aggregate and give the window an ORDER BY, and each row sums everything up to itself:
sum(revenue) OVER (ORDER BY month). each bar is the one before plus that month. the last one is the year's total, 4,166,616.SELECT month, revenue,
sum(revenue) OVER (ORDER BY month) AS running_total,
sum(revenue) OVER (PARTITION BY extract(year FROM month) ORDER BY month) AS year_to_date
FROM monthly
ORDER BY month;| monthdate | revenuenumeric | running_totalnumeric | year_to_datenumeric |
|---|---|---|---|
| 2025-07-01 | 348021.73 | 348021.73 | 348021.73 |
| 2025-08-01 | 360384.79 | 708406.52 | 708406.52 |
| 2025-09-01 | 342888.77 | 1051295.29 | 1051295.29 |
| 2025-10-01 | 358400.90 | 1409696.19 | 1409696.19 |
| 2025-11-01 | 354606.47 | 1764302.66 | 1764302.66 |
| 2025-12-01 | 346452.85 | 2110755.51 | 2110755.51 |
| 2026-01-01 | 352732.50 | 2463488.01 | 352732.50 |
| 2026-02-01 | 331476.19 | 2794964.20 | 684208.69 |
| 2026-03-01 | 355904.75 | 3150868.95 | 1040113.44 |
| 2026-04-01 | 355887.10 | 3506756.05 | 1396000.54 |
| 2026-05-01 | 353582.15 | 3860338.20 | 1749582.69 |
| 2026-06-01 | 306277.84 | 4166616.04 | 2055860.53 |
the second column restarts in january: PARTITION BY the year makes each year its own window. and a moving total is the same idea with a frame that also forgets: the last three months, not all of them.
- 1SELECT month, revenue,
- 2 array_agg(month) OVER w AS frame,
- 3 sum(revenue) OVER w AS total
- 4FROM monthly
- 5WINDOW w AS (ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
- 6ORDER BY month;
| month | revenue | total |
|---|---|---|
| 2025-07-01 | 348021.73 | 348021.73 |
| 2025-08-01 | 360384.79 | 708406.52 |
| 2025-09-01 | 342888.77 | 1051295.29 |
| 2025-10-01 | 358400.90 | 1409696.19 |
| 2025-11-01 | 354606.47 | 1764302.66 |
| 2025-12-01 | 346452.85 | 2110755.51 |
| 2026-01-01 | 352732.50 | 2463488.01 |
| 2026-02-01 | 331476.19 | 2794964.20 |
| 2026-03-01 | 355904.75 | 3150868.95 |
| 2026-04-01 | 355887.10 | 3506756.05 |
| 2026-05-01 | 353582.15 | 3860338.20 |
| 2026-06-01 | 306277.84 | 4166616.04 |
month 2025-12-01: 6 rows in the frame (2025-07-01, 2025-08-01, 2025-09-01, 2025-10-01, 2025-11-01, 2025-12-01). a running total: the frame starts at the first month and ends at this one, so it grows by a month every row.
SELECT month,
round(avg(revenue) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)) AS avg_3_months
FROM monthly
ORDER BY month
LIMIT 4;| monthdate | avg_3_monthsnumeric |
|---|---|
| 2025-07-01 | 348022 |
| 2025-08-01 | 354203 |
| 2025-09-01 | 350432 |
| 2025-10-01 | 353891 |
why ROWS there? because a frame can count rows or measure values, and it matters the moment your data has ties or holes. window frames is that story; here's the short version.
the row before isn't yesterday
lag reads the previous row. if a day has no row, the previous row is two days ago, and lag won't tell you.
-- events has no rows at all on 2026-04-14
SELECT * FROM (
SELECT day, day - lag(day) OVER (ORDER BY day) AS gap
FROM (SELECT DISTINCT occurred_at::date AS day FROM events) AS d
) AS g
WHERE day = '2026-04-15';or skip the WHERE and sort by the gap, so the hole floats to the top:
SELECT day, day - lag(day) OVER (ORDER BY day) AS gap
FROM (SELECT DISTINCT occurred_at::date AS day FROM events) AS d
ORDER BY gap DESC NULLS LAST, day
LIMIT 3;| daydate | gapint4 |
|---|---|
| 2026-04-15 | 2 |
| 2026-03-02 | 1 |
| 2026-03-03 | 1 |
2026-04-15 is 2 days after the day before it, every other day is 1. that's the start of gaps and islands. and when you want "yesterday" to mean yesterday, make a row for every day first, with a calendar from generate_series.
keylines
- lag(x, n, default) reads x from n rows back in the window's order. lead reads ahead.
- no row there means the default (NULL unless you say otherwise).
- sum(x) OVER (ORDER BY ...) is a running total. PARTITION BY restarts it.
- the default frame includes ties: for one step per row, use ROWS and a unique order.
- the previous row isn't the previous day. fill the calendar first.