Window Frame (ROWS BETWEEN)
advancedwindow-functions
2 min read
What is a Window Frame?
The window frame clause specifies which rows relative to the current row are included in the window function's calculation. It controls the "window of visibility" for functions like SUM, AVG, FIRST_VALUE, etc.
Syntax
window_function() OVER (
PARTITION BY col
ORDER BY col
ROWS BETWEEN start AND end
)Frame boundaries:
UNBOUNDED PRECEDING— from the first row of the partitionN PRECEDING— N rows before the current rowCURRENT ROW— the current rowN FOLLOWING— N rows after the current rowUNBOUNDED FOLLOWING— through the last row of the partition
When to Use
- Moving averages and rolling sums
- Cumulative totals (UNBOUNDED PRECEDING to CURRENT ROW)
- Centered windows (N PRECEDING to N FOLLOWING)
Key Points
- Default Frame — With ORDER BY, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
- ROWS vs RANGE — ROWS counts physical rows. RANGE includes all rows with the same ORDER BY value.
- GROUPS — PostgreSQL 11+ supports GROUPS, which counts groups of tied values.
- LAST_VALUE Trap — The default frame makes LAST_VALUE return the current row. Use UNBOUNDED FOLLOWING.
- Performance — Narrower frames are slightly more efficient.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
Window Frame (ROWS BETWEEN) Challenge
Write a query that solve this task: calculate a running total of order amounts.
Expected result
Each order with a running total of amounts up to and including the current row.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What is a Window Frame?
Initializing database...Each run starts from fresh sample data.
More Examples
Centered 3-row average
Average the row before, current, and row after.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
What is the difference between ROWS and RANGE?
ROWS counts physical rows. RANGE groups rows with identical ORDER BY values together. For unique ORDER BY values, they behave the same.
Can I use a window frame without ORDER BY?
A frame clause requires ORDER BY. Without ORDER BY, all rows are in one unordered group and the frame encompasses all rows.