โช๏ธ Window Frames #3
A window frame decides which rows a window function uses for each row's calculation. Frames are what turn a plain SUM into a running total or a moving average, and a misunderstood default frame is behind some of the most confusing window results.
This is the third tutorial on windows. It builds on Window Functions and LEAD & LAG.
1. Sample Data
store_sales holds daily revenue for two stores:
CREATE OR REPLACE TEMP VIEW store_sales AS
SELECT * FROM VALUES
('S1', DATE'2024-03-01', 100),
('S1', DATE'2024-03-02', 120),
('S1', DATE'2024-03-03', 90),
('S1', DATE'2024-03-04', 150),
('S1', DATE'2024-03-05', 110),
('S2', DATE'2024-03-01', 200),
('S2', DATE'2024-03-02', 180),
('S2', DATE'2024-03-03', 210)
AS store_sales(store, sale_date, revenue)
transactions holds payments for one account. Two payments happen on the same day (January 2nd), and there is no payment on January 4th. Both details matter later:
CREATE OR REPLACE TEMP VIEW transactions AS
SELECT * FROM VALUES
(1, DATE'2024-01-01', 100),
(2, DATE'2024-01-02', 50),
(3, DATE'2024-01-02', 30),
(4, DATE'2024-01-03', 70),
(5, DATE'2024-01-05', 20)
AS transactions(txn_id, txn_date, amount)
2. What Is a Frame?
When Spark computes a window function, it works through the rows one at a time. The row it is working on is the current row. The frame is the set of rows, relative to the current row, that the function looks at.
-- Syntax
function(...) OVER (
PARTITION BY ...
ORDER BY ...
ROWS BETWEEN start AND end
)
start and end can be:
| Boundary | Meaning |
|---|---|
UNBOUNDED PRECEDING | The first row of the partition |
n PRECEDING | n rows before the current row |
CURRENT ROW | The current row |
n FOLLOWING | n rows after the current row |
UNBOUNDED FOLLOWING | The last row of the partition |
So ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means "this row and the two before it". The frame never crosses a partition boundary.
Frames apply to aggregate functions (SUM, AVG, MIN, MAX, COUNT) and to FIRST_VALUE and LAST_VALUE. Ranking functions and LAG/LEAD do not use frames.
3. Running Totals
A running total adds up everything from the start of the partition to the current row:
SELECT store,
sale_date,
revenue,
SUM(revenue) OVER (
PARTITION BY store
ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM store_sales
ORDER BY store, sale_date
+-----+----------+-------+-------------+
|store|sale_date |revenue|running_total|
+-----+----------+-------+-------------+
|S1 |2024-03-01|100 |100 |
|S1 |2024-03-02|120 |220 |
|S1 |2024-03-03|90 |310 |
|S1 |2024-03-04|150 |460 |
|S1 |2024-03-05|110 |570 |
|S2 |2024-03-01|200 |200 |
|S2 |2024-03-02|180 |380 |
|S2 |2024-03-03|210 |590 |
+-----+----------+-------+-------------+
S1's running total grows 100, 220, 310 and so on. Because of PARTITION BY store, the total resets to 200 when S2 starts. Drop PARTITION BY and you get one running total across both stores, which is rarely what you want.
4. Moving Averages
A moving (rolling) average uses a fixed number of recent rows. Here is a 3-day moving average: the current day plus the two before it. COUNT(*) over the same frame shows how many rows went into each average:
SELECT store,
sale_date,
revenue,
ROUND(AVG(revenue) OVER (
PARTITION BY store ORDER BY sale_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
), 2) AS moving_avg_3d,
COUNT(*) OVER (
PARTITION BY store ORDER BY sale_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS rows_in_frame
FROM store_sales
ORDER BY store, sale_date
+-----+----------+-------+-------------+-------------+
|store|sale_date |revenue|moving_avg_3d|rows_in_frame|
+-----+----------+-------+-------------+-------------+
|S1 |2024-03-01|100 |100.0 |1 |
|S1 |2024-03-02|120 |110.0 |2 |
|S1 |2024-03-03|90 |103.33 |3 |
|S1 |2024-03-04|150 |120.0 |3 |
|S1 |2024-03-05|110 |116.67 |3 |
|S2 |2024-03-01|200 |200.0 |1 |
|S2 |2024-03-02|180 |190.0 |2 |
|S2 |2024-03-03|210 |196.67 |3 |
+-----+----------+-------+-------------+-------------+
The first two days of each store do not have two earlier rows, so their frames are smaller. On March 1st the "average" is just that day's revenue. If you only want full 3-day averages, keep rows where rows_in_frame = 3 (filter in an outer query or CTE).
5. Looking Ahead: Centered and Whole-Partition Frames
Frames can include rows after the current one. A centered window uses one row on each side, which smooths out spikes:
SELECT store,
sale_date,
revenue,
ROUND(AVG(revenue) OVER (
PARTITION BY store ORDER BY sale_date
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
), 2) AS centered_avg,
SUM(revenue) OVER (
PARTITION BY store ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS store_total
FROM store_sales
ORDER BY store, sale_date
+-----+----------+-------+------------+-----------+
|store|sale_date |revenue|centered_avg|store_total|
+-----+----------+-------+------------+-----------+
|S1 |2024-03-01|100 |110.0 |570 |
|S1 |2024-03-02|120 |103.33 |570 |
|S1 |2024-03-03|90 |120.0 |570 |
|S1 |2024-03-04|150 |116.67 |570 |
|S1 |2024-03-05|110 |130.0 |570 |
|S2 |2024-03-01|200 |190.0 |590 |
|S2 |2024-03-02|180 |196.67 |590 |
|S2 |2024-03-03|210 |195.0 |590 |
+-----+----------+-------+------------+-----------+
UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING covers the whole partition, so store_total is the same on every row of a store: 570 for S1 and 590 for S2.
6. The Default Frame (and the Ties Trap)
If you do not write a frame, Spark picks one for you, and the choice depends on whether the window has an ORDER BY:
| Window | Default frame | Effect of SUM |
|---|---|---|
OVER (PARTITION BY x) | The whole partition | Group total on every row |
OVER (PARTITION BY x ORDER BY y) | RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW | Running total |
The second default uses RANGE, not ROWS. With RANGE, "current row" includes every row that has the same ORDER BY value as the current row. When the order column has ties, those rows are treated as one step.
Compare the default with an explicit ROWS frame on transactions, where two payments share January 2nd:
SELECT txn_id,
txn_date,
amount,
SUM(amount) OVER (ORDER BY txn_date) AS default_frame,
SUM(amount) OVER (ORDER BY txn_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_frame
FROM transactions
ORDER BY txn_date, txn_id
+------+----------+------+-------------+----------+
|txn_id|txn_date |amount|default_frame|rows_frame|
+------+----------+------+-------------+----------+
|1 |2024-01-01|100 |100 |100 |
|2 |2024-01-02|50 |180 |150 |
|3 |2024-01-02|30 |180 |180 |
|4 |2024-01-03|70 |250 |250 |
|5 |2024-01-05|20 |270 |270 |
+------+----------+------+-------------+----------+
With the default frame, both January 2nd payments show 180: each one includes the other, because they tie on txn_date. With ROWS, the running total moves one row at a time (150, then 180).
Common mistake: Relying on the default frame for running totals. If the
ORDER BYcolumn can have duplicates, the default gives tied rows the same total. WriteROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWexplicitly, and add a tie breaker (heretxn_id) to theORDER BYso the row order is predictable.
7. The LAST_VALUE Trap
FIRST_VALUE and LAST_VALUE return the first and last value in the frame. With the default frame, the frame ends at the current row, so LAST_VALUE just returns the current row's value:
SELECT store,
sale_date,
revenue,
LAST_VALUE(revenue) OVER (PARTITION BY store ORDER BY sale_date) AS last_default,
LAST_VALUE(revenue) OVER (
PARTITION BY store ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_in_store
FROM store_sales
ORDER BY store, sale_date
+-----+----------+-------+------------+-------------+
|store|sale_date |revenue|last_default|last_in_store|
+-----+----------+-------+------------+-------------+
|S1 |2024-03-01|100 |100 |110 |
|S1 |2024-03-02|120 |120 |110 |
|S1 |2024-03-03|90 |90 |110 |
|S1 |2024-03-04|150 |150 |110 |
|S1 |2024-03-05|110 |110 |110 |
|S2 |2024-03-01|200 |200 |210 |
|S2 |2024-03-02|180 |180 |210 |
|S2 |2024-03-03|210 |210 |210 |
+-----+----------+-------+------------+-------------+
last_default simply copies revenue. Extending the frame to UNBOUNDED FOLLOWING gives the real last value of each store: 110 for S1 and 210 for S2.
FIRST_VALUE does not have this problem, because the default frame always starts at the first row of the partition.
8. ROWS vs RANGE with Offsets
ROWS counts rows. RANGE looks at the values in the ORDER BY column. With an offset, RANGE means "rows whose order value is within this distance of the current row's value".
This query sums each payment with the payments from the previous day, once with ROWS and once with RANGE:
SELECT txn_id,
txn_date,
amount,
SUM(amount) OVER (ORDER BY txn_date, txn_id
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS this_and_prev_row,
SUM(amount) OVER (ORDER BY txn_date
RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) AS this_and_prev_day
FROM transactions
ORDER BY txn_date, txn_id
+------+----------+------+-----------------+-----------------+
|txn_id|txn_date |amount|this_and_prev_row|this_and_prev_day|
+------+----------+------+-----------------+-----------------+
|1 |2024-01-01|100 |100 |100 |
|2 |2024-01-02|50 |150 |180 |
|3 |2024-01-02|30 |80 |180 |
|4 |2024-01-03|70 |100 |150 |
|5 |2024-01-05|20 |90 |20 |
+------+----------+------+-----------------+-----------------+
When the ORDER BY column is a DATE, a RANGE offset of 1 PRECEDING means one day earlier.
Look at the January 5th payment. The previous row is January 3rd (70), so this_and_prev_row is 90. But the previous day, January 4th, has no payments, so this_and_prev_day is just 20. RANGE respects gaps in the dates; ROWS does not.
Also compare the January 3rd payment: RANGE adds both January 2nd payments (50 and 30) to its own 70, giving 150, while ROWS only adds the single previous row.
Common mistake: Writing
INTERVAL 1 DAY PRECEDINGon aDATEcolumn. Spark 3.5 rejects it, because interval offsets only work withTIMESTAMPcolumns:
SELECT txn_id,
SUM(amount) OVER (ORDER BY txn_date
RANGE BETWEEN INTERVAL 1 DAY PRECEDING AND CURRENT ROW) AS this_and_prev_day
FROM transactions
[DATATYPE_MISMATCH.RANGE_FRAME_INVALID_TYPE] Cannot resolve "(ORDER BY txn_date ASC NULLS FIRST RANGE BETWEEN INTERVAL '1' DAY PRECEDING AND CURRENT ROW)" due to data type mismatch: The data type "DATE" used in the order specification does not match the data type "INTERVAL DAY" which is used in the range frame.; line 2 pos 24;
Use a plain number for DATE columns. For a TIMESTAMP column, intervals such as RANGE BETWEEN INTERVAL 1 HOUR PRECEDING AND CURRENT ROW work.
ROWS | RANGE | |
|---|---|---|
| Counts | Physical rows | Distance in the ORDER BY value |
| Tied rows | Each row is its own step | Tied rows are in each other's frame |
| Gaps in dates | Ignored | Respected |
| Typical use | Running totals, "last N rows" | "Last 7 days", value-based windows |
9. Try It in the Online Compiler
Copy this into the PySpark Online Compiler. Each spark.sql() call holds one statement:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Spark SQL Window Frames").getOrCreate()
spark.sql("""
CREATE OR REPLACE TEMP VIEW store_sales AS
SELECT * FROM VALUES
('S1', DATE'2024-03-01', 100),
('S1', DATE'2024-03-02', 120),
('S1', DATE'2024-03-03', 90),
('S1', DATE'2024-03-04', 150),
('S1', DATE'2024-03-05', 110),
('S2', DATE'2024-03-01', 200),
('S2', DATE'2024-03-02', 180),
('S2', DATE'2024-03-03', 210)
AS store_sales(store, sale_date, revenue)
""")
# Running total and 3-day moving average per store
spark.sql("""
SELECT store, sale_date, revenue,
SUM(revenue) OVER (PARTITION BY store ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
ROUND(AVG(revenue) OVER (PARTITION BY store ORDER BY sale_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS moving_avg_3d
FROM store_sales
ORDER BY store, sale_date
""").show(truncate=False)
# Last value of each store, with a frame that covers the whole partition
spark.sql("""
SELECT store, sale_date, revenue,
LAST_VALUE(revenue) OVER (PARTITION BY store ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_in_store
FROM store_sales
ORDER BY store, sale_date
""").show(truncate=False)
Summary
- A frame is the set of rows, around the current row, that a window function uses. Write it as
ROWS BETWEEN start AND end. - Running total:
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Moving average of 3 rows:ROWS BETWEEN 2 PRECEDING AND CURRENT ROW. PARTITION BYmakes running totals reset for each group.- Without
ORDER BY, the default frame is the whole partition. WithORDER BY, it isRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which gives tied rows the same result. LAST_VALUEneedsROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWINGto return the partition's last value.ROWScounts rows;RANGEmeasures distance in theORDER BYvalue, so it respects gaps such as missing days.
Next, you will learn GROUPING SETS, ROLLUP and CUBE for subtotals and grand totals in one query.