← All lessons
Advanced SQL · Lesson 3 of 11

Running totals, LAG and LEAD

An aggregate with OVER (ORDER BY …) gives a running total: each row adds up everything up to and including itself. Shipped revenue building up over time:

WITH totals AS (
  SELECT o.id, o.ordered_on, SUM(i.qty * p.price) AS total
  FROM orders o
  JOIN order_items i ON i.order_id = o.id
  JOIN products p ON p.id = i.product_id
  WHERE o.status = 'shipped'
  GROUP BY o.id, o.ordered_on
)
SELECT ordered_on, total,
  SUM(total) OVER (ORDER BY ordered_on) AS running_total
FROM totals
ORDER BY ordered_on;
Returns
ordered_on | total | running_total
-----------+-------+--------------
2024-09-01 | 49    | 49
2024-09-03 | 40    | 89
2024-09-10 | 47.25 | 136.25
2024-09-15 | 93.5  | 229.75
2024-09-20 | 59    | 288.75
2024-10-05 | 9.75  | 298.5
2024-10-07 | 50    | 348.5
2024-10-11 | 81.5  | 430
(8 rows)

Which rows count is set by the window's frame. You can name it: ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means this row and the two before it, which gives a moving average over three rows. With only an ORDER BY, the default frame treats rows that tie in the ORDER BY as one step, which surprises people; write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to go strictly row by row.

SELECT id, ordered_on,
  COUNT(*) OVER (ORDER BY ordered_on ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS in_frame,
  MIN(ordered_on) OVER (ORDER BY ordered_on ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS frame_starts
FROM orders
ORDER BY ordered_on
LIMIT 4;
Returns
id  | ordered_on | in_frame | frame_starts
----+------------+----------+-------------
101 | 2024-09-01 | 1        | 2024-09-01
102 | 2024-09-03 | 2        | 2024-09-01
103 | 2024-09-10 | 3        | 2024-09-01
104 | 2024-09-12 | 3        | 2024-09-03
(4 rows)

LAG(x) reads x from the row before in the window, and LEAD(x) from the row after. The first row's LAG is NULL. They answer "change since last time" questions. Days between each of Ana's and Ben's orders:

SELECT customer_id, ordered_on,
  LAG(ordered_on) OVER (PARTITION BY customer_id ORDER BY ordered_on) AS previous,
  julianday(ordered_on) - julianday(LAG(ordered_on) OVER (PARTITION BY customer_id ORDER BY ordered_on)) AS days_since
FROM orders
WHERE customer_id IN (1, 2)
ORDER BY customer_id, ordered_on;
Returns
customer_id | ordered_on | previous   | days_since
------------+------------+------------+-----------
1           | 2024-09-01 | NULL       | NULL
1           | 2024-09-10 | 2024-09-01 | 9
1           | 2024-10-05 | 2024-09-10 | 25
2           | 2024-09-03 | NULL       | NULL
2           | 2024-09-20 | 2024-09-03 | 17
(5 rows)

LAG(x, 2) looks two rows back, and LAG(x, 1, 0) gives 0 instead of NULL when there's no row. Finally, x / SUM(x) OVER () is each row's share of the whole. Each category's share of all products:

SELECT category, COUNT(*) AS products,
  ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct
FROM products
GROUP BY category
ORDER BY products DESC, category;
Returns
category | products | pct
---------+----------+-----
Garden   | 3        | 37.5
Books    | 2        | 25
Clothing | 2        | 25
Outdoors | 1        | 12.5
(4 rows)

Practice

Every order, oldest first: its id, ordered_on, and a running count of orders so far (1, 2, 3 …). Sort by ordered_on.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

SUM(x) OVER (ORDER BY d)A running total.
ROWS BETWEEN n PRECEDING AND CURRENT ROWA frame of this row and n before: moving sums and averages.
LAG(x), LEAD(x)x from the row before, the row after.
LAG(x, n, default)n rows back, with a default instead of NULL.
x / SUM(x) OVER ()Share of the total.

The other AI and data engineering courses