29. Window frames: running totals, moving averages, lag and lead

Choose exactly which rows a window function sees from each row: everything so far, the last three, the one before.

A table of sales to work on

This chapter works on each order's total, again and again. To keep the examples short, we first save the totals of the orders that were not cancelled into a table of their own, sale, with CREATE TABLE ... AS SELECT (a new table made from a query's result). Chapter 30 shows a better way to keep a query: a view.

CREATE TABLE sale AS
SELECT o.id, o.customer_id, o.ordered, sum(oi.qty * oi.price) AS total
FROM orders AS o JOIN order_item AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY o.id;

SELECT * FROM sale ORDER BY ordered;
idcustomer_idorderedtotal
112026-09-02180.0
222026-09-05165.0
312026-09-12175.0
432026-09-20300.0
652026-10-03290.0
722026-10-10235.0
862026-10-15390.0
972026-10-22490.0
1012026-10-2845.0
1182026-11-02300.0
1242026-11-05175.0
1362026-11-1190.0
1572026-11-25375.0
13 rows

13 orders: orders 5 and 14 were cancelled, so they aren't there.

Running totals

A running total adds up everything from the first row to this one: the takings of the month so far, a bank balance after each transaction. With a window function it is just sum() with ORDER BY inside OVER:

SELECT id, ordered, total,
       sum(total) OVER (ORDER BY ordered) AS running_total
FROM sale
ORDER BY ordered;
idorderedtotalrunning_total
12026-09-02180.0180.0
22026-09-05165.0345.0
32026-09-12175.0520.0
42026-09-20300.0820.0
62026-10-03290.01110.0
72026-10-10235.01345.0
82026-10-15390.01735.0
92026-10-22490.02225.0
102026-10-2845.02270.0
112026-11-02300.02570.0
122026-11-05175.02745.0
132026-11-1190.02835.0
152026-11-25375.03210.0
13 rows

Each row's running_total is its own total plus all the ones before it: 180, then 180 + 165 = 345, then 520, and so on up to 3210, the takings of all 13 orders.

Why does it add only up to this row, when in chapter 28 avg(price) OVER () saw every row? Because of the frame. A frame is the part of the window that the function sees from the current row. When OVER has an ORDER BY, the frame starts at the first row and ends at the current row, so sum() becomes a running sum. Without ORDER BY, the frame is the whole window.

With PARTITION BY, the running total starts again for each group. Here is how much each customer has spent so far, order by order:

SELECT customer_id, id, ordered, total,
       sum(total) OVER (PARTITION BY customer_id ORDER BY ordered) AS customer_so_far
FROM sale
ORDER BY customer_id, ordered;
customer_ididorderedtotalcustomer_so_far
112026-09-02180.0180.0
132026-09-12175.0355.0
1102026-10-2845.0400.0
222026-09-05165.0165.0
272026-10-10235.0400.0
342026-09-20300.0300.0
4122026-11-05175.0175.0
562026-10-03290.0290.0
682026-10-15390.0390.0
6132026-11-1190.0480.0
792026-10-22490.0490.0
7152026-11-25375.0865.0
8112026-11-02300.0300.0
13 rows

Customer 1 spent 180, then 355 after the second order, then 400; customer 7 has spent 865 in two orders.

Choosing the frame: ROWS BETWEEN

You can say exactly which rows the frame holds with ROWS BETWEEN start AND end. The start and end can be:

WrittenMeans
UNBOUNDED PRECEDINGthe first row of the window
n PRECEDINGn rows before this one
CURRENT ROWthis row
n FOLLOWINGn rows after this one
UNBOUNDED FOLLOWINGthe last row of the window

A moving average of the last 3 orders evens out the ups and downs, to show where the takings are heading. The frame is "2 rows before, up to this row":

SELECT id, ordered, total,
       count(*) OVER (ORDER BY ordered ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS n,
       round(avg(total) OVER (ORDER BY ordered ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS avg_last_3
FROM sale
ORDER BY ordered;
idorderedtotalnavg_last_3
12026-09-02180.01180.0
22026-09-05165.02172.5
32026-09-12175.03173.33
42026-09-20300.03213.33
62026-10-03290.03255.0
72026-10-10235.03275.0
82026-10-15390.03305.0
92026-10-22490.03371.67
102026-10-2845.03308.33
112026-11-02300.03278.33
122026-11-05175.03173.33
132026-11-1190.03188.33
152026-11-25375.03213.33
13 rows

n shows how many rows were in the frame: the first order has only itself (1), the second has 2, and from the third on there are always 3. When order 10 comes in at only 45 baht, the average of the last three drops from 371.67 to 308.33.

Near the start, a frame holds fewer rows than you asked for, as the first two rows here show. A "3-order average" on the first row is really the average of one order. If that would mislead, show count(*) beside it as here, or leave those rows out.

The default frame and the last_value() trap

first_value(x) gives x from the first row of the frame, last_value(x) from its last row. Try to find the cheapest and the dearest product:

SELECT name, price,
       first_value(name) OVER (ORDER BY price, name) AS cheapest,
       last_value(name)  OVER (ORDER BY price, name) AS dearest
FROM product
ORDER BY price, name;
namepricecheapestdearest
Pen15.0PenPen
Highlighter25.0PenHighlighter
Potato Chips25.0PenPotato Chips
Notebook30.0PenNotebook
Croissant35.0PenCroissant
Orange Juice40.0PenOrange Juice
Green Tea45.0PenGreen Tea
Coffee55.0PenCoffee
Banana Bread60.0PenBanana Bread
Dried Mango90.0PenDried Mango
Cheesecake120.0PenCheesecake
Cashew Nuts150.0PenCashew Nuts
12 rows

cheapest is right, Pen on every row. But dearest is each row's own name! This is the trap beginners fall into most with windows: with ORDER BY in OVER, the default frame ends at the current row, so the last row of the frame is the current row itself. The fix is to say the frame should run to the end of the window:

SELECT name, price,
       last_value(name) OVER (ORDER BY price, name
                              ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS dearest
FROM product
ORDER BY price, name;
namepricedearest
Pen15.0Cashew Nuts
Highlighter25.0Cashew Nuts
Potato Chips25.0Cashew Nuts
Notebook30.0Cashew Nuts
Croissant35.0Cashew Nuts
Orange Juice40.0Cashew Nuts
Green Tea45.0Cashew Nuts
Coffee55.0Cashew Nuts
Banana Bread60.0Cashew Nuts
Dried Mango90.0Cashew Nuts
Cheesecake120.0Cashew Nuts
Cashew Nuts150.0Cashew Nuts
12 rows

Now every row says Cashew Nuts.

nth_value(x, n) gives x from row n of the frame. With the same whole-window frame, it can find the second cheapest product of each category; first_value here needs no frame, because the first row is always in the default frame:

SELECT category_id, name, price,
       first_value(name)  OVER (PARTITION BY category_id ORDER BY price) AS cheapest,
       nth_value(name, 2) OVER (PARTITION BY category_id ORDER BY price
                                ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second
FROM product
ORDER BY category_id, price;
category_idnamepricecheapestsecond
1Orange Juice40.0Orange JuiceGreen Tea
1Green Tea45.0Orange JuiceGreen Tea
1Coffee55.0Orange JuiceGreen Tea
2Croissant35.0CroissantBanana Bread
2Banana Bread60.0CroissantBanana Bread
2Cheesecake120.0CroissantBanana Bread
3Potato Chips25.0Potato ChipsDried Mango
3Dried Mango90.0Potato ChipsDried Mango
3Cashew Nuts150.0Potato ChipsDried Mango
4Pen15.0PenHighlighter
4Highlighter25.0PenHighlighter
4Notebook30.0PenHighlighter
12 rows

lag() and lead(): the row before, the row after

lag(x) gives x from the row before this one, lead(x) from the row after. They don't use the frame; they just step back or forward in the window's order. That makes "how much has it changed since last time?" easy:

SELECT id, ordered, total,
       lag(total)  OVER (ORDER BY ordered) AS previous,
       total - lag(total) OVER (ORDER BY ordered) AS change,
       lead(ordered) OVER (ORDER BY ordered) AS next_order
FROM sale
ORDER BY ordered;
idorderedtotalpreviouschangenext_order
12026-09-02180.0NULLNULL2026-09-05
22026-09-05165.0180.0-15.02026-09-12
32026-09-12175.0165.010.02026-09-20
42026-09-20300.0175.0125.02026-10-03
62026-10-03290.0300.0-10.02026-10-10
72026-10-10235.0290.0-55.02026-10-15
82026-10-15390.0235.0155.02026-10-22
92026-10-22490.0390.0100.02026-10-28
102026-10-2845.0490.0-445.02026-11-02
112026-11-02300.045.0255.02026-11-05
122026-11-05175.0300.0-125.02026-11-11
132026-11-1190.0175.0-85.02026-11-25
152026-11-25375.090.0285.0NULL
13 rows

The first row has no row before it, so previous is NULL, and change is NULL too (anything with NULL is NULL). The biggest fall is order 10, 445 baht less than order 9. The last row has no next_order.

lag takes two more arguments: how many rows back (1 if you leave it out) and what to give when there is no such row instead of NULL. With PARTITION BY it looks back only within the group, so it can tell how many days each customer waited between orders:

SELECT customer_id, id, ordered,
       lag(ordered) OVER (PARTITION BY customer_id ORDER BY ordered) AS before,
       julianday(ordered) - julianday(lag(ordered) OVER (PARTITION BY customer_id ORDER BY ordered)) AS days_between,
       lag(total, 1, 0) OVER (PARTITION BY customer_id ORDER BY ordered) AS before_total
FROM sale
ORDER BY customer_id, ordered;
customer_ididorderedbeforedays_betweenbefore_total
112026-09-02NULLNULL0
132026-09-122026-09-0210.0180.0
1102026-10-282026-09-1246.0175.0
222026-09-05NULLNULL0
272026-10-102026-09-0535.0165.0
342026-09-20NULLNULL0
4122026-11-05NULLNULL0
562026-10-03NULLNULL0
682026-10-15NULLNULL0
6132026-11-112026-10-1527.0390.0
792026-10-22NULLNULL0
7152026-11-252026-10-2234.0490.0
8112026-11-02NULLNULL0
13 rows

Customer 1 came back after 10 days, then after 46. Each customer's first order has no before, and before_total shows 0, the value we asked for, instead of NULL.

The WINDOW clause, RANGE and GROUPS

When several functions use the same window, writing it out again and again is long and easy to get wrong. Name it once in a WINDOW clause (after HAVING, before ORDER BY) and use the name after OVER:

SELECT id, ordered, total,
       count(*)   OVER last3 AS n,
       sum(total) OVER last3 AS sum_last_3,
       max(total) OVER last3 AS max_last_3
FROM sale
WINDOW last3 AS (ORDER BY ordered ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
ORDER BY ordered;
idorderedtotalnsum_last_3max_last_3
12026-09-02180.01180.0180.0
22026-09-05165.02345.0180.0
32026-09-12175.03520.0180.0
42026-09-20300.03640.0300.0
62026-10-03290.03765.0300.0
72026-10-10235.03825.0300.0
82026-10-15390.03915.0390.0
92026-10-22490.031115.0490.0
102026-10-2845.03925.0490.0
112026-11-02300.03835.0490.0
122026-11-05175.03520.0300.0
132026-11-1190.03565.0300.0
152026-11-25375.03640.0375.0
13 rows

ROWS counts rows. There are two other ways to measure a frame:

The orders and takings of the 7 days up to each order:

SELECT id, ordered, total,
       count(*)   OVER week AS orders_in_7_days,
       sum(total) OVER week AS total_in_7_days
FROM sale
WINDOW week AS (ORDER BY julianday(ordered) RANGE BETWEEN 6 PRECEDING AND CURRENT ROW)
ORDER BY ordered;
idorderedtotalorders_in_7_daystotal_in_7_days
12026-09-02180.01180.0
22026-09-05165.02345.0
32026-09-12175.01175.0
42026-09-20300.01300.0
62026-10-03290.01290.0
72026-10-10235.01235.0
82026-10-15390.02625.0
92026-10-22490.01490.0
102026-10-2845.02535.0
112026-11-02300.02345.0
122026-11-05175.02475.0
132026-11-1190.02265.0
152026-11-25375.01375.0
13 rows

Order 8 (15 October) sees order 7 from 5 days before, so 2 orders, 625 baht. Order 3 (12 September) is exactly 7 days after order 2, just outside the frame, so it sees only itself.

The difference shows when the ORDER BY has ties. Highlighter and Potato Chips both cost 25:

SELECT name, price,
       sum(price) OVER (ORDER BY price, id ROWS UNBOUNDED PRECEDING) AS rows_sum,
       sum(price) OVER (ORDER BY price RANGE UNBOUNDED PRECEDING) AS range_sum,
       count(*)   OVER (ORDER BY price GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS near_prices
FROM product
ORDER BY price, id;
namepricerows_sumrange_sumnear_prices
Pen15.015.015.03
Potato Chips25.040.065.04
Highlighter25.065.065.04
Notebook30.095.095.04
Croissant35.0130.0130.03
Orange Juice40.0170.0170.03
Green Tea45.0215.0215.03
Coffee55.0270.0270.03
Banana Bread60.0330.0330.03
Dried Mango90.0420.0420.03
Cheesecake120.0540.0540.03
Cashew Nuts150.0690.0690.02
12 rows

(ROWS UNBOUNDED PRECEDING is short for "from the first row to this one".) With ROWS, Potato Chips' running sum is 40 and Highlighter's is 65, one row at a time. With RANGE, both get 65: rows of the same price are peers, and a peer is always in the frame with the current row. This is also the default frame: when you write only ORDER BY, you get RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. near_prices counts the products in this price group and the price groups either side: Pen sees itself and the two at 25, 3 in all.

A running total over a column with ties (say, several orders on the same day) gives the tied rows the same total, because of the default RANGE. If you want it to grow row by row, write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW and add something that can't tie, such as id, to the ORDER BY.

  1. Show each customer in the order they joined, with how many members the shop had after each one joined.
  2. For each order in sale, show the total of the same customer's previous order.
  3. For each order in sale, add up its total and the total of the order just before it.
Show the answer
SELECT name, joined, count(*) OVER (ORDER BY joined) AS members_so_far
FROM customer
ORDER BY joined;

SELECT customer_id, id, ordered, total,
       lag(total) OVER (PARTITION BY customer_id ORDER BY ordered) AS previous_total
FROM sale
ORDER BY customer_id, ordered;

SELECT id, ordered, total,
       sum(total) OVER (ORDER BY ordered ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS last_two
FROM sale
ORDER BY ordered;
namejoinedmembers_so_far
Somchai Jaidee2025-01-151
Malee Srisuk2025-03-022
Anan Wongsa2025-04-203
Pim Chaiya2025-06-114
Narin Thongdee2025-08-305
Kanya Boonmee2025-10-056
Wichai Saelim2026-01-097
Siriporn Kaewdee2026-02-148
Tawan Rungruang2026-05-219
Lalita Meesuk2026-08-0310
10 rows
customer_ididorderedtotalprevious_total
112026-09-02180.0NULL
132026-09-12175.0180.0
1102026-10-2845.0175.0
222026-09-05165.0NULL
272026-10-10235.0165.0
342026-09-20300.0NULL
4122026-11-05175.0NULL
562026-10-03290.0NULL
682026-10-15390.0NULL
6132026-11-1190.0390.0
792026-10-22490.0NULL
7152026-11-25375.0490.0
8112026-11-02300.0NULL
13 rows
idorderedtotallast_two
12026-09-02180.0180.0
22026-09-05165.0345.0
32026-09-12175.0340.0
42026-09-20300.0475.0
62026-10-03290.0590.0
72026-10-10235.0525.0
82026-10-15390.0625.0
92026-10-22490.0880.0
102026-10-2845.0535.0
112026-11-02300.0345.0
122026-11-05175.0475.0
132026-11-1190.0265.0
152026-11-25375.0465.0
13 rows

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made