Looking across rows

Part of the free LogicWiz Data Engineering course, Module 2: SQL for pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 8:55 on Thursday. Every morning Tess asks the same three questions: how did yesterday compare with the day before, how much have we made so far this month, and is the trend going up? Your first running total gives the first payment of June, $68.74, a total of $347.03. In a spreadsheet you would point at the cell above; in SQL, you point with a window.

You'll learn to

  • Compare each row with the previous one using LAG and LEAD
  • Build running totals and moving averages with a written frame
  • Avoid the default-frame trap and the missing-day trap
  • Say how many rows a frame makes Postgres hold

Learn

Point at the row above

Take Tess's first question: how did yesterday compare with the day before?

You already have one row per day with its revenue. What each row needs is the revenue from the row before it, sitting next to its own.

LAG(revenue) OVER (ORDER BY day) does that: it returns revenue from the previous row in day order. Its twin LEAD returns the next one. No self-join is needed.

  • The first row has no previous row, so LAG gives NULL there. LEAD gives NULL on the last.
  • LAG(revenue, 7) looks seven rows back: a week ago, if there is exactly one row per day.
  • LAG(revenue, 1, 0) returns 0 instead of NULL when there is no previous row.

Yesterday next to today

WITH daily AS (
  SELECT DATE(paid_ts) AS day, SUM(amount) AS revenue
  FROM payments
  WHERE status = 'captured'
  GROUP BY DATE(paid_ts)
)
SELECT day, revenue,
       LAG(revenue) OVER (ORDER BY day) AS prev_revenue,
       revenue - LAG(revenue) OVER (ORDER BY day) AS change,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY day))
             / NULLIF(LAG(revenue) OVER (ORDER BY day), 0), 1) AS pct_change
FROM daily
ORDER BY day;

Each row now carries yesterday's revenue, the change, and the change in percent. NULLIF(x, 0) turns a zero into NULL, so a day after a zero-revenue day gives NULL instead of a division-by-zero error.

The first four days

dayrevenueprevrevenuechangepctchange
2025-06-01347.03NULLNULLNULL
2025-06-02415.80347.0368.7719.8
2025-06-03549.87415.80134.0732.2
2025-06-04607.44549.8757.5710.5

The first day has nothing to compare with, so every derived column is NULL. That is correct. Do not replace it with 0, which would claim "no change".

The same, for each customer

Add PARTITION BY customer_id, and LAG looks back within each customer's own orders. It restarts for every customer.

Subtract the two dates and you get the days since that customer's previous order. Churn models love this number, and so do interviewers ("the average time between a customer's first and second purchase").

The first order of every customer gets NULL, because there is no previous one. Customer 23 ordered twice on 11 June, so one gap is 0 days, which is right.

Days between a customer's orders

SELECT customer_id, order_id, order_ts,
       DATE(order_ts) - LAG(DATE(order_ts)) OVER (
         PARTITION BY customer_id
         ORDER BY order_ts
       ) AS days_since_prev
FROM orders
WHERE customer_id IN (13, 23)
ORDER BY customer_id, order_ts;

Subtracting two dates in Postgres gives a whole number of days.

A frame: the rows you add up

Tess's other two questions need more than one neighbour. "So far this month" adds up every day from the first to today. "The trend" averages the last few days.

For that, put OVER after an aggregate. It then works on a frame: the set of rows around the current one that it is allowed to read.

  • Running total: SUM(revenue) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). Every row from the start up to this one.
  • 3-day moving average: AVG(revenue) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW). This row and the two before it. It smooths out a noisy day, so the trend shows.

A three-row frame slides down June

Five days of June revenue in a column; a frame of the current row and the two before it moves down one day at a time, and the 3-day average is worked out at each step.

  1. 1 June. The frame wants this row and the two before it, but nothing comes before it. One row: the average is 347.03.

  2. 2 June. Two rows in the frame: (347.03 + 415.80) / 2 = 381.42. Still a partial average.

  3. 3 June. The frame is full: (347.03 + 415.80 + 549.87) / 3 = 437.57.

  4. 4 June. The frame slides. 1 June drops out and 4 June comes in: (415.80 + 549.87 + 607.44) / 3 = 524.37.

The green and blue rows are inside the frame. The first two days average fewer than three rows: say so on the chart, or start the line from day 3.

Play with a frame

A window function computed one row at a time over a small table of salaries: SUM with no frame written adds tied rows together, AVG uses a ROWS frame of the current and the previous row, and LAG reads the row before.

This simulator uses a small table of salaries. Pick AVG and step through the rows to watch a ROWS frame of the current row and the one before it. Pick LAG to see which row it reads. Then pick SUM: with no frame written, the two tied salaries share one running total. The next section explains why.

Month to date and the 3-day trend

WITH daily AS (
  SELECT DATE(paid_ts) AS day, SUM(amount) AS revenue
  FROM payments
  WHERE status = 'captured'
  GROUP BY DATE(paid_ts)
)
SELECT day, revenue,
       SUM(revenue) OVER (
         ORDER BY day
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS month_to_date,
       ROUND(AVG(revenue) OVER (
         ORDER BY day
         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
       ), 2) AS avg_3d
FROM daily
ORDER BY day;

The running total ends at 8514.73, the same as SUM(amount) over all captured payments: a free check that nothing was lost.

Remember: LAG reads one row back. An aggregate with OVER reads a frame. Write the frame out with ROWS BETWEEN ... every time.

The first payment showed the whole day

Now the wrong number from this morning. Your running total gave payment 5002, the first payment of June at $68.74, a total of $347.03.

The query said SUM(amount) OVER (ORDER BY day), with no frame. SQL then uses a default: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.

RANGE means "all rows whose ORDER BY value is less than or equal to mine". So rows with the same day are added together. On a table with one row per day you never notice. On a table with several payments per day, every payment of 1 June shows the whole of 1 June.

ROWS counts actual rows, one at a time. Write it out and the question never comes up.

Same sum, two frames

SELECT payment_id, DATE(paid_ts) AS day, amount,
       SUM(amount) OVER (ORDER BY DATE(paid_ts)) AS default_frame,
       SUM(amount) OVER (
         ORDER BY DATE(paid_ts), payment_id
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS rows_frame
FROM payments
WHERE status = 'captured'
ORDER BY DATE(paid_ts), payment_id
LIMIT 8;

In default_frame, all four payments of 1 June show 347.03. In rows_frame the total grows payment by payment. Notice the tie-breaker payment_id: without it, the order inside a day is not defined.

Three rows are not three days

One more surprise hides in the words "3-day average". A frame of 2 PRECEDING is three rows, not three days.

Bank transfers were captured on only five days in two weeks. So on the bank-transfer rows, the "3-day" average for 10 June really averages 5, 7 and 10 June.

The fix is a calendar. Generate every day with generate_series, LEFT JOIN the data to it, and turn the gaps into 0 with COALESCE. Now one row really is one day, and LAG and moving averages mean what they say.

The "3-day" average for 10 June

A timeline of June: bank transfers exist on 4, 5, 7, 10 and 12 June. Without a calendar the three-row frame for 10 June reaches back to 5 June; with a calendar it covers 8, 9 and 10 June.

Each block starts at its day of June. The red frame holds three rows but spans six days; the green one holds three rows and three days.

Fill the gaps first, then average

WITH days AS (
  SELECT CAST(d AS DATE) AS day
  FROM generate_series(DATE '2025-06-01', DATE '2025-06-14', INTERVAL '1 day') AS d
),
bank AS (
  SELECT DATE(paid_ts) AS day, SUM(amount) AS revenue
  FROM payments
  WHERE status = 'captured'
    AND method = 'bank_transfer'
  GROUP BY DATE(paid_ts)
)
SELECT days.day,
       COALESCE(bank.revenue, 0) AS revenue,
       ROUND(AVG(COALESCE(bank.revenue, 0)) OVER (
         ORDER BY days.day
         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
       ), 2) AS avg_3d
FROM days
LEFT JOIN bank ON bank.day = days.day
ORDER BY days.day;

Fourteen rows, one per day, zeros included. Drop the calendar and you get five rows and a moving average that quietly spans a week.

The trap: two quiet mistakes. A window with ORDER BY but no frame uses RANGE, which lumps together rows with equal values. And a frame counts rows, not days, so a gap in the data stretches your "3-day" average. Write ROWS BETWEEN ... every time, and build a calendar when days can be missing.

The same windows in DuckDB

import duckdb

rows = duckdb.sql("""
    WITH daily AS (
        SELECT CAST(paid_ts AS DATE) AS day, ROUND(SUM(amount), 2) AS revenue
        FROM read_json_auto('data/payments.jsonl')
        WHERE status = 'captured'
        GROUP BY day
    )
    SELECT day, revenue,
           LAG(revenue) OVER (ORDER BY day) AS prev_revenue,
           ROUND(SUM(revenue) OVER (
               ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
           ), 2) AS month_to_date
    FROM daily
    ORDER BY day
    LIMIT 3
""").fetchall()
for day, revenue, prev_revenue, month_to_date in rows:
    print(day, revenue, prev_revenue, month_to_date)

The window syntax is identical in DuckDB, here on the JSON export. The amounts in that file are floating-point numbers, so round sums before you print or compare them.

Under the hood: how many rows wait

What does a frame cost? After the Sort from Lesson 2.3, the WindowAgg reads rows into a holding area called a tuplestore. It lives in work_mem and moves to a temporary file when it outgrows it. Think of a waiting room: a row can leave only when its answer is known.

How many rows wait depends on the frame.

  • ROWS BETWEEN 2 PRECEDING AND CURRENT ROW needs three rows. LAG(x, 7) needs eight.
  • RANGE, the default once there is an ORDER BY, must read ahead to the last peer before it can answer for the first. A running total by day holds a whole day.
  • An aggregate with no ORDER BY, such as SUM(amount) OVER (PARTITION BY day) or OVER (), needs the whole partition before its first row can leave.

Three frames, three buffers

-- a sliding ROWS frame: a few rows
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT payment_id,
       SUM(amount) OVER (ORDER BY payment_id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
FROM big_payments;

-- the default RANGE frame by day: a whole day of peers
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT payment_id, SUM(amount) OVER (ORDER BY day)
FROM big_payments;

-- no ORDER BY at all: the whole table is one partition
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT payment_id, SUM(amount) OVER ()
FROM big_payments;

Look at each WindowAgg's Storage line: Memory for the first two and Disk for the third. Postgres 18 prints this line in EXPLAIN ANALYZE. The sorts underneath spill too (external merge): 100,000 rows do not fit in 4 MB here.

What each frame kept in the buffer

Bars compare the window buffer for 100,000 payments: 17 kB for a three-row frame, 312 kB for a running total by day, and 4,096 kB on disk for a sum over the whole table.

One bar per query above: the buffer grows from three rows, to a day of peers, to the whole table. These are the Maximum Storage values EXPLAIN ANALYZE printed, with work_mem at 4 MB.

A sliding sum: one in, one out

When the frame slides one row down, Postgres does not add up the whole frame again. It adds the row that enters and takes away the row that leaves. This is called moving-aggregate mode, and it needs an aggregate that can undo a value: one with an inverse transition function.

A 7-row moving sum over a million rows is about 2 million steps, not 7 million.

SUM, COUNT and AVG can undo. MIN and MAX cannot: you cannot "un-max" a value. So whenever the start of the frame moves, Postgres recomputes them over the whole frame. A 30-day moving maximum over hourly data re-reads all 720 rows of its frame for every row, where a moving sum takes 2 steps.

Which aggregates can slide?

SELECT p.proname AS aggregate,
       a.aggminvtransfn::regproc AS inverse_function
FROM pg_aggregate a
JOIN pg_proc p ON p.oid = a.aggfnoid
WHERE p.proname IN ('sum', 'avg', 'count', 'max', 'min')
  AND pg_get_function_arguments(p.oid) IN ('numeric', '"any"')
ORDER BY p.proname;

Postgres's own tables about its functions say it. sum and avg remove a value with numeric_accum_inv, and count with int8dec_any. max and min show -: no inverse.

Numbers to remember

WhatNumber or nameWhat it means
LAG(x, n, default)n rows back, default when there is noneLAG(revenue, 7) is a week ago only if there is one row per day
The default frame with ORDER BYRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWRows equal on the ORDER BY (peers) are added together
A 7-day moving averageROWS BETWEEN 6 PRECEDING AND CURRENT ROWSeven rows: the current one and the 6 before it
Storage: Memory Maximum Storage: 17kBA three-row ROWS frame over 100,000 paymentsPostgres 18 prints this line; Storage: Disk means the buffer spilled
A running total by day, default frame312 kBOne day of peers waits: about 7,143 payments
OVER ()4,096 kB, Storage: DiskAll 100,000 rows wait, and the buffer outgrew workmem (4 MB)
Moving SUM, COUNT, AVGOne add and one remove per rowThe docs put it as run time proportional to the rows, not rows times frame length
Moving MIN, MAXRecomputed over the whole frameThey have no inverse function
The same windows in PySparkF.lag, Window.rowsBetweenModule 11

What changed at SwiftKart

Tess's morning table now answers all three questions in one query: each day's revenue, the change from the day before, the month to date and a 3-day average. The month-to-date column ends at $8,514.73, the number you reconciled in Lesson 2.1.

Payment 5002 shows a running total of $68.74, because the frame is written out. And the bank-transfer trend sits on a calendar, so three rows are three days.

The product team is next. They want to know how many sessions the app had, and nobody stored a session id. Lesson 2.6 builds sessions, streaks and retention out of LAG and a running sum.

In one line

LAG and LEAD read neighbouring rows; write ROWS BETWEEN for running totals and moving averages, because the default frame is RANGE; fill missing days before you trust a moving window.

Interview corner

How do you compute month-over-month growth in SQL?

Aggregate to one row per month in a CTE, then use LAG(revenue) OVER (ORDER BY month) to bring the previous month alongside. Growth is (revenue - prev) / NULLIF(prev, 0). The first month has no previous value, so it stays NULL, and missing months should be filled from a calendar first.

What is the difference between ROWS and RANGE in a window frame?

ROWS counts physical rows around the current one. RANGE works on the values of the ORDER BY column, so rows with equal values are peers and are always included together. The default frame with an ORDER BY is RANGE ... CURRENT ROW, which is why a running total over duplicate dates jumps; I always write ROWS explicitly.

How would you calculate a 7-day rolling average of daily active users?

Count distinct users per day, left join that to a calendar so every day exists, then AVG(dau) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). The first six days have partial windows; depending on the use, I either show them or start the series on day 7.

A window query over a huge table writes gigabytes of temporary files. Where does the memory go, and how do you shrink it?

Two places: the Sort that orders rows for the window, and the WindowAgg's tuplestore, which buffers rows the frame still needs and spills past work_mem. A sliding ROWS frame holds only its few rows; a RANGE frame holds a whole peer group; an aggregate with no ORDER BY holds the whole partition before it outputs anything. I would write an explicit ROWS frame, replace a whole-partition aggregate with a GROUP BY joined back, and prefer SUM, COUNT and AVG, which slide with an inverse function, over MIN and MAX, which are recomputed as the frame moves. Postgres 18 shows Storage: Disk on the WindowAgg when this happens.