Skip to content
Silver 7 min read · Windows 3 practice problems ↓

Running totals and window frames

Revenue so far this month, a 3-day moving average, each order's share of the total: all three are aggregates over a window. This lesson explains the one idea behind them, the frame, and the default frame that surprises almost everyone.

Foundations · SQL for data engineers · Silver · Window functions, lesson 3 of 3

Read first: LAG and LEAD (skip if you know it)

In plain words first

A running total is what you would write in a notebook: for each order, the total of that order and every order before it.

Spark SQL · Revenue so far, order by order

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT order_date, order_id, amount,
       sum(amount) OVER (ORDER BY order_date, order_id) AS running_total
FROM orders
ORDER BY order_date, order_id

The only change from the city total in the ranking lesson is ORDER BY inside OVER. With an ORDER BY, the sum no longer covers the whole group; it covers the rows from the start up to the current row. The last row, 4160, is the grand total.

Add PARTITION BY and each group gets its own running total, starting again from zero:

Spark SQL · A running total per city

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT city, order_id, amount,
       sum(amount) OVER (
         PARTITION BY city ORDER BY order_date, order_id
       ) AS city_running
FROM orders
ORDER BY city, order_date, order_id

The frame: which rows to add up

The set of rows a window functionwindow function: A function computed over a group of rows, written with OVER (...), that keeps every row instead of collapsing them like GROUP BY. Learn more → uses for the current row is called its frame. You can write it out yourself. These are the pieces:

You writeMeans
UNBOUNDED PRECEDINGFrom the first row of the partition
2 PRECEDINGFrom two rows before the current one
CURRENT ROWThe current row
1 FOLLOWINGUp to one row after
UNBOUNDED FOLLOWINGUp to the last row of the partition

So ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is a running total, and ROWS BETWEEN 2 PRECEDING AND CURRENT ROW is "this row and the two before it": a moving window.

The default frame, and the tie surprise

If you give ORDER BY but no frame, Spark (like most databases) uses RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE means "every row whose ORDER BY value is up to the current one", so rows that tie are added together. Order by the date alone and see:

Spark SQL · ORDER BY the date only: tied rows share a total

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT order_date, order_id, amount,
       sum(amount) OVER (ORDER BY order_date) AS running_by_date
FROM orders
ORDER BY order_date, order_id

Both orders of 1 March show 1070, not 420 and then 1070. Neither is wrong, but they answer different questions: "revenue up to the end of this day" versus "revenue up to this order". Choose on purpose:

  • Per order: add a unique tie-breaker (ORDER BY order_date, order_id), or write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
  • Per day: aggregateaggregate: A function that turns many rows into one value: count, sum, avg, min, max. With GROUP BY it gives one value per group. Learn more → to one row per day first, then take the running total of the days.

Moving averages

A moving average smooths a noisy daily number. First one row per day, then average this day and the two before it:

Spark SQL · Average of the last 3 rows

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
WITH daily AS (
  SELECT order_date, sum(amount) AS revenue
  FROM orders
  GROUP BY order_date
)
SELECT order_date, revenue,
       round(avg(revenue) OVER (
         ORDER BY order_date
         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
       ), 1) AS avg_last_3_rows
FROM daily
ORDER BY order_date

The first two days average over fewer rows (one, then two), because there is nothing further back. That is usually fine, but say so when you present the numbers.

ROWS counts rows; RANGE counts values

There were no orders on 3 March. "The last 3 rows" on the 4th therefore reaches back to the 1st. "The last 3 days" should only cover the 2nd to the 4th. A RANGE frame measures distance in the ORDER BY value instead of in rows. Here the value is a day number, so 2 PRECEDING means "up to 2 days earlier":

Spark SQL · Last 3 rows versus last 3 calendar days

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
WITH daily AS (
  SELECT order_date, sum(amount) AS revenue
  FROM orders
  GROUP BY order_date
)
SELECT order_date, revenue,
       sum(revenue) OVER (
         ORDER BY order_date
         ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
       ) AS last_3_rows,
       sum(revenue) OVER (
         ORDER BY datediff(order_date, '2026-01-01')
         RANGE BETWEEN 2 PRECEDING AND CURRENT ROW
       ) AS last_3_days
FROM daily
ORDER BY order_date

On the 4th: the last 3 rows are the 1st, 2nd and 4th (2730); the last 3 days are the 2nd, 3rd and 4th (840 + 0 + 820 = 1660). On the 6th they agree again, because the 4th, 5th and 6th all had orders.

Tip: On a real date column Spark also accepts an interval: ORDER BY order_date RANGE BETWEEN INTERVAL 2 DAYS PRECEDING AND CURRENT ROW. The day-number form above works in every engine.

Percent of total

With no ORDER BY there is no frame to worry about: the window is the whole partition. Divide by it to get each row's share:

Spark SQL · Each order's share of its city

Input: orders

order_idcustomer_idcityamountorder_date
2011Pune4202026-03-01
2022Delhi6502026-03-01
2031Pune3002026-03-02
2043Pune5402026-03-02
2052Delhi2802026-03-04
2064Pune5402026-03-04
2075Mumbai3902026-03-05
2081Pune1802026-03-05
2092Delhi6502026-03-06
2105Mumbai2102026-03-06
SELECT order_id, city, amount,
       round(100.0 * amount / sum(amount) OVER (PARTITION BY city), 1) AS pct_of_city
FROM orders
ORDER BY city, order_id

Multiply by 100.0, not 100, so the division is never done on whole numbers in engines that would round it away.

Common mistakes

  • Ordering a running total by a column with ties — The default RANGE frame adds tied rows together. Add a tie-breaker, or use ROWS.
  • Using ROWS when you mean days — Missing days make "the last 7 rows" span more than 7 days. Use RANGE on a day number, or fill the days first.
  • last_value() returning the current row — The default frame ends at the current row, so last_value sees itself. Write ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
  • Adding ORDER BY to a percent-of-total window — It turns the total into a running total. Leave ORDER BY out when you want the whole partition.

Key takeaways

  • SUM(...) OVER (ORDER BY ...) is a running total; add PARTITION BY to restart per group.
  • The frame chooses which rows count: ROWS BETWEEN n PRECEDING AND CURRENT ROW is a moving window.
  • With ORDER BY and no frame, the default is RANGE ... CURRENT ROW: ties are added together.
  • ROWS counts rows; RANGE measures the ORDER BY value, so gaps in dates matter.
  • Without ORDER BY the window is the whole partition: use it for percent of total.

Interview prep

THE QUESTION

"Compute a 7-day moving average of daily revenue."

Aggregate to one row per day, then avg(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). Then raise the two catches. Days with no sales have no row, so ROWS would span more than 7 calendar days: either join to a calendar first (with zero revenue, which also changes the average), or use a RANGE frame on the date. And the first six days average over fewer than 7 days; if that is misleading, return NULL until 7 days exist, for example with a count over the same frame.

Avoid: sum(amount) OVER (ORDER BY order_date) as "the running total per order". With several orders on one day, the default RANGE frame gives them all the end-of-day total, so the numbers do not grow order by order.

Follow-ups · answer out loud, then open

Follow-up"What is the default frame of a window with ORDER BY?"
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: from the start of the partition to the current row and every row that ties with it. Without ORDER BY the frame is the whole partition. That is why last_value often returns the current row: its frame ends there.
Scenario"A 7-day moving average looks too smooth for a store that is closed on Sundays."
Sundays have no row, so ROWS BETWEEN 6 PRECEDING spans 8 calendar days. Decide what the average means: over open days (keep ROWS), or over calendar days (join to a calendar with zero, or use a RANGE frame over the date). Say which one the report shows.
Trap"Can a running total be computed without a window function?"
Yes, with a self join on b.ts <= a.ts and a SUM, but it compares every pair of rows, so it is quadratic. A window function sorts once and adds in one pass. Use the self join only where windows are not available.

Check yourself

4 questions

Without a frame, what does sum(x) OVER (ORDER BY d) compute?

Show the answer

A running total, with ties on d added together. The default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.

Which frame is "this row and the 6 before it"?

Show the answer

ROWS BETWEEN 6 PRECEDING AND CURRENT ROW. 6 before plus the current row is 7 rows.

Days 1, 2 and 4 have rows. On day 4, which days does ROWS BETWEEN 2 PRECEDING AND CURRENT ROW cover?

Show the answer

1, 2, 4. ROWS counts rows, and day 3 has no row.

You want each order's share of its city total. What goes in OVER?

Show the answer

PARTITION BY city. Without ORDER BY the window is the whole city.

Practise this

Problems that use this, graded on hidden tests

See all 4 problems →

Keep going

Up next · new module: Structure, sets and dates · 6 min read
CTEs and subqueries
Write a long query as named steps with WITH, and use scalar and correlated subqueries where they fit.

Related lessons

Previous: LAG and LEAD

Primary sources: Window functions and frames