skip to content

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.

value =
query.sql
  1. 1SELECT month, revenue,
  2. 2 lag(month) OVER w AS read_from,
  3. 3 lag(revenue) OVER w AS value
  4. 4FROM monthly
  5. 5WINDOW w AS (ORDER BY month)
  6. 6ORDER BY month;
the rows of the window, with the frame of the current row marked
monthrevenuevalue
2025-07-01348021.73null
2025-08-01360384.79348021.73
2025-09-01342888.77360384.79
2025-10-01358400.90342888.77
2025-11-01354606.47358400.90
2025-12-01346452.85354606.47
2026-01-01352732.50346452.85
2026-02-01331476.19352732.50
2026-03-01355904.75331476.19
2026-04-01355887.10355904.75
2026-05-01353582.15355887.10
2026-06-01306277.84353582.15
(12 rows in, 12 rows out)
current rowthe row it reads

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.

month 4/12
real output, postgres 18.6 (PGlite 0.5.12) · lag-and-lead
step through the months and switch the function. the arrow points at the row that was read, and that row's revenue lands in 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):

sqldb=shop · session monthly
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;
output, from postgres 18.6
#1 · CREATE VIEW
#2 · SELECT 12
monthdaterevenuenumericchangenumericpctnumeric
2025-07-01348021.73nullnull
2025-08-01360384.7912363.063.6
2025-09-01342888.77-17496.02-4.9
2025-10-01358400.9015512.134.5
2025-11-01354606.47-3794.43-1.1
2025-12-01346452.85-8153.62-2.3
2026-01-01352732.506279.651.8
2026-02-01331476.19-21256.31-6.0
2026-03-01355904.7524428.567.4
2026-04-01355887.10-17.650.0
2026-05-01353582.15-2304.95-0.6
2026-06-01306277.84-47304.31-13.4
(12 rows)

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:

sqldb=shop · session monthly
continues session monthly (1 earlier block run first)
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;
output, from postgres 18.6
SELECT 3
monthdateprev_or_zeronumericnext_monthdate
2025-07-0102025-08-01
2025-08-01348021.732025-09-01
2025-09-01360384.792025-10-01
(3 rows)

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:

2025-07348,022
2025-08708,407
2025-091,051,295
2025-101,409,696
2025-111,764,303
2025-122,110,756
2026-012,463,488
2026-022,794,964
2026-033,150,869
2026-043,506,756
2026-053,860,338
2026-064,166,616
revenue so far, month by month: 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.
sqldb=shop · session monthly
continues session monthly (2 earlier blocks run first)
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;
output, from postgres 18.6
SELECT 12
monthdaterevenuenumericrunning_totalnumericyear_to_datenumeric
2025-07-01348021.73348021.73348021.73
2025-08-01360384.79708406.52708406.52
2025-09-01342888.771051295.291051295.29
2025-10-01358400.901409696.191409696.19
2025-11-01354606.471764302.661764302.66
2025-12-01346452.852110755.512110755.51
2026-01-01352732.502463488.01352732.50
2026-02-01331476.192794964.20684208.69
2026-03-01355904.753150868.951040113.44
2026-04-01355887.103506756.051396000.54
2026-05-01353582.153860338.201749582.69
2026-06-01306277.844166616.042055860.53
(12 rows)

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.

sum =
query.sql
  1. 1SELECT month, revenue,
  2. 2 array_agg(month) OVER w AS frame,
  3. 3 sum(revenue) OVER w AS total
  4. 4FROM monthly
  5. 5WINDOW w AS (ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
  6. 6ORDER BY month;
the rows of the window, with the frame of the current row marked
monthrevenuetotal
2025-07-01348021.73348021.73
2025-08-01360384.79708406.52
2025-09-01342888.771051295.29
2025-10-01358400.901409696.19
2025-11-01354606.471764302.66
2025-12-01346452.852110755.51
2026-01-01352732.502463488.01
2026-02-01331476.192794964.20
2026-03-01355904.753150868.95
2026-04-01355887.103506756.05
2026-05-01353582.153860338.20
2026-06-01306277.844166616.04
(12 rows in, 12 rows out)
current rowin the frame

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.

month 6/12
real output, postgres 18.6 (PGlite 0.5.12) · lag-and-lead
step through the months and switch the frame. the running total's frame grows by a month every row. the moving one slides: always this month and the two before, so its total stays near three months' worth.
sqldb=shop · session monthly
continues session monthly (3 earlier blocks run first)
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;
output, from postgres 18.6
SELECT 4
monthdateavg_3_monthsnumeric
2025-07-01348022
2025-08-01354203
2025-09-01350432
2025-10-01353891
(4 rows)

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.

predict the output
sql
-- 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:

sqldb=events
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;
output, from postgres 18.6
SELECT 3
daydategapint4
2026-04-152
2026-03-021
2026-03-031
(3 rows)

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.