Part 07 / Topic 6 of 8
Window frames
The frame is which rows of the partition the function actually sees, relative to the current row. You've now met both defaults:
- Without ORDER BY, the frame is the whole partition — the share-of-total shape.
- With ORDER BY, the frame runs from the partition start to the current row — running totals, and the LAST_VALUE surprise.
ROWS BETWEEN ... AND ... sets it explicitly. The everyday use: moving averages — here, each month's revenue smoothed over itself and its previous month:
WITH monthly AS (
SELECT date_trunc('month', o.order_date)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY 1
)
SELECT month, revenue,
round(avg(revenue) OVER (ORDER BY month
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW), 2) AS two_month_avg
FROM monthly
ORDER BY month;
month | revenue | two_month_avg
------------+---------+---------------
2025-01-01 | 2069.00 | 2069.00
2025-02-01 | 135.00 | 1102.00
2025-03-01 | 150.00 | 142.50
2025-04-01 | 1709.00 | 929.50
(4 rows)
ROWS counts physical rows; RANGE groups peers with equal ORDER BY values (that's the actual default: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which is why tied rows share running totals); GROUPS counts distinct ORDER BY values. ROWS with explicit bounds is what you'll write 95% of the time.
🧪 Quick quiz — answer from memory, then check.
- Spell the frame for "this row and the two before it".
- What is the default frame once a window has an ORDER BY?
Show the answers
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW.RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW— start of partition up to the current row (including its ORDER-BY peers).
Exercise 6: Smoothed months
What to do: The same monthly revenue, with a two-month moving average (each month averaged with its predecessor).
Sample output:
month | revenue | two_month_avg
------------+---------+---------------
2025-01-01 | 2069.00 | 2069.00
2025-02-01 | 135.00 | 1102.00
2025-03-01 | 150.00 | 142.50
2025-04-01 | 1709.00 | 929.50
(4 rows)
💡 Hint: ROWS BETWEEN 1 PRECEDING AND CURRENT ROW.
Show the solution to Exercise 6
-- Exercise 6: Smoothed months
WITH monthly AS (
SELECT date_trunc('month', o.order_date)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY 1
)
SELECT month, revenue,
round(avg(revenue) OVER (ORDER BY month
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW), 2) AS two_month_avg
FROM monthly
ORDER BY month;