Running totals, LAG and LEAD

Topic 3 of 3 in Window functions11 min readBeginnerFree course

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:

SQL
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;
Text
   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.

Running totals, LAG and LEAD. A table of months and orders: 2026-01 with 3 orders, 2026-02 with 3, 2026-03 with 3, 2026-04 with 2 and 2026-05 with 2. The running_total column, sum(orders) OVER (ORDER BY month), is 3, 6, 9, 11, 13. The previous column, lag(orders) OVER (ORDER BY month), is NULL, 3, 3, 3, 2 — the value from the previous row. A dashed box around the orders for January to April shows the window frame for the April row: every row up to and including it, so 3 + 3 + 3 + 2 = 11. Frame examples: sum(orders) OVER (ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW); avg(orders) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) for a 3-month moving average; lead(orders) OVER (ORDER BY month) for the value from the next row. With ORDER BY in the window, aggregates become cumulative, and the frame clause says exactly which rows count. lag and lead return NULL where there is no previous or next row, or a default such as lag(orders, 1, 0).

Window frames

The set of rows an ordered window function looks at for each row is called its frame. You can set it explicitly:

SQL
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:

SQL
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;
Text
   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:

SQL
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;
Text
 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:

SQL
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;
Text
   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:

SQL
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;
Text
   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?

SQL
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;
Text
 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:

SQL
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;
Text
 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), the ORDER BY inside OVER (and whether it has ties), and the frame (which rows around the current one are included).

Exercise

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.

SQL
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;

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.