Frame clauses are what actually control which rows a window function sees — and the defaults aren't always what you'd expect. This lesson teaches you to write precise ROWS BETWEEN and RANGE BETWEEN expressions so your rolling totals, running sums, and moving averages do exactly what you intend.

You've written a window function before. Maybe you used SUM() OVER (PARTITION BY customer_id ORDER BY order_date) to build a running total, or reached for LAG() to compare yesterday's sales to today's. Those expressions work — but do you actually know which rows they're looking at when they compute the result? The answer isn't always obvious, and when you get it wrong, you end up with totals that drift, averages that skew, or rolling calculations that silently include too many rows. The frame clause is the tool that puts you in control.
By the end of this lesson, you'll be able to write precise ROWS BETWEEN and RANGE BETWEEN expressions from scratch, understand why the same aggregate can produce wildly different results depending on the frame, and confidently pick the right frame for rolling averages, running totals, and boundary-aware calculations.
What you'll learn:
ROWS BETWEEN and RANGE BETWEEN — and when each one bites youUNBOUNDED PRECEDING, CURRENT ROW, N PRECEDING, and N FOLLOWINGThis lesson assumes you're comfortable with the basics of window functions — specifically OVER(), PARTITION BY, and ORDER BY inside a window. If you haven't worked with those yet, start with Window Functions: RANK, ROW_NUMBER, and LAG and Aggregating Across Groups with SQL Window Functions: SUM, AVG, and COUNT OVER PARTITION BY first. Those two lessons establish the vocabulary this one builds on.
When a window function evaluates a row, it doesn't necessarily look at every row in the partition. It looks at a subset of the partition — a sliding window of rows relative to the current row. That subset is the window frame.
Think of it like a spotlight moving across a stage. The partition defines which actors are on stage at all. The frame defines which actors the spotlight is currently illuminating. As the spotlight moves from row to row, the set of illuminated rows changes according to the rules you've defined.
Here's the key insight that trips up most people: if you write ORDER BY inside your OVER() clause but don't write an explicit frame clause, SQL doesn't use all the rows in the partition. It uses a default frame, and that default is almost never what beginners expect.
The default frame when ORDER BY is present is:
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
That sounds reasonable until you realize RANGE BETWEEN CURRENT ROW doesn't mean "the current physical row" — it means "all rows with the same value as the current row in the ORDER BY column." We'll unpack exactly why that matters in a moment.
Key insight
Every window function that uses ORDER BY has a frame clause, whether you wrote one or not. The default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Writing your own frame clause isn't optional polish — it's how you make your intent explicit and avoid hidden bugs.
A frame clause has two parts: the frame mode and the frame extent.
<frame_mode> BETWEEN <start_bound> AND <end_bound>
Frame mode is either ROWS or RANGE (there's also GROUPS, covered in the advanced lesson). This tells SQL how to count the boundaries.
Frame extent is defined by two boundary expressions:
UNBOUNDED PRECEDING — from the very first row in the partitionN PRECEDING — N rows (or N units of the ORDER BY value) before the current rowCURRENT ROW — the current row itselfN FOLLOWING — N rows (or N units) after the current rowUNBOUNDED FOLLOWING — all the way to the last row in the partitionYou can combine these however you need, as long as the start bound is not later than the end bound. So 3 PRECEDING AND 1 PRECEDING is valid (a window that excludes the current row), but 1 FOLLOWING AND 1 PRECEDING is not.
ROWS mode counts actual, physical rows. When you say ROWS BETWEEN 2 PRECEDING AND CURRENT ROW, you're saying: "look at me and the two rows above me in the sorted result — no matter what values they hold."
Let's make this concrete. Imagine you're working with daily website traffic data:
CREATE TABLE daily_traffic (
traffic_date DATE,
page_views INT
);
INSERT INTO daily_traffic VALUES
('2024-01-01', 1200),
('2024-01-02', 980),
('2024-01-03', 1540),
('2024-01-04', 2200),
('2024-01-05', 1875),
('2024-01-06', 1300),
('2024-01-07', 1650);
You want a 3-day rolling average to smooth out day-to-day noise. The frame should include the current day and the two days before it.
SELECT
traffic_date,
page_views,
ROUND(
AVG(page_views) OVER (
ORDER BY traffic_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
),
1
) AS rolling_3day_avg
FROM daily_traffic
ORDER BY traffic_date;
| traffic_date | page_views | rolling_3day_avg |
|---|---|---|
| 2024-01-01 | 1200 | 1200.0 |
| 2024-01-02 | 980 | 1090.0 |
| 2024-01-03 | 1540 | 1240.0 |
| 2024-01-04 | 2200 | 1573.3 |
| 2024-01-05 | 1875 | 1871.7 |
| 2024-01-06 | 1300 | 1791.7 |
| 2024-01-07 | 1650 | 1608.3 |
Notice that January 1st only averages itself (there are no preceding rows), and January 2nd averages two rows. The frame shrinks gracefully at the edges. This is called a partial frame and it's the default behavior — the function works with whatever rows are available within the partition.
Tip
When building rolling averages in reporting, ROWS BETWEEN is almost always your friend. The count of physical rows is predictable and easy to reason about, especially when your data has consistent daily or weekly granularity. For time-series work at this level, also check out Temporal Data Mastery: Writing Queries for Time-Series, Date Ranges, and Slowly Changing Dimensions for the broader toolkit.
The most common use of frame clauses in production SQL is the running total — a cumulative sum where each row shows the total of all values from the beginning up to and including that row.
SELECT
traffic_date,
page_views,
SUM(page_views) OVER (
ORDER BY traffic_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS cumulative_views
FROM daily_traffic
ORDER BY traffic_date;
UNBOUNDED PRECEDING anchors the start of the frame at the very first row in the partition (or the entire result set if there's no PARTITION BY). CURRENT ROW closes it at the row being calculated. As each new row is processed, the frame grows by one.
This is exactly what the default RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW would produce in this specific case — because all dates are unique. But when dates aren't unique, the two modes diverge. That's what we'll look at next.
RANGE mode doesn't count rows — it counts values. When you say RANGE BETWEEN CURRENT ROW AND CURRENT ROW, you mean "all rows where the ORDER BY column has the same value as the current row," not just the single physical row you're on.
This distinction only matters when there are ties — rows with identical values in the ORDER BY column.
Let's construct a scenario where this bites you. Suppose you're tracking orders, and two orders arrive on the same day:
CREATE TABLE sales_orders (
order_id INT,
order_date DATE,
amount DECIMAL(10,2)
);
INSERT INTO sales_orders VALUES
(1, '2024-02-01', 500.00),
(2, '2024-02-01', 300.00),
(3, '2024-02-02', 450.00),
(4, '2024-02-03', 800.00),
(5, '2024-02-03', 200.00);
Now run the same running total using the implicit default (which is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW):
SELECT
order_id,
order_date,
amount,
SUM(amount) OVER (
ORDER BY order_date
) AS running_total_range -- default frame, RANGE mode
FROM sales_orders
ORDER BY order_date, order_id;
| order_id | order_date | amount | running_total_range |
|---|---|---|---|
| 1 | 2024-02-01 | 500.00 | 800.00 |
| 2 | 2024-02-01 | 300.00 | 800.00 |
| 3 | 2024-02-02 | 450.00 | 1250.00 |
| 4 | 2024-02-03 | 800.00 | 2250.00 |
| 5 | 2024-02-03 | 200.00 | 2250.00 |
Orders 1 and 2 both show 800.00 — the total for both orders on February 1st — even though order 1 "came first." That's RANGE treating both rows with the same order_date as a single logical position. The same thing happens for orders 4 and 5.
Now switch to ROWS:
SELECT
order_id,
order_date,
amount,
SUM(amount) OVER (
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total_rows
FROM sales_orders
ORDER BY order_date, order_id;
| order_id | order_date | amount | running_total_rows |
|---|---|---|---|
| 1 | 2024-02-01 | 500.00 | 500.00 |
| 2 | 2024-02-01 | 300.00 | 800.00 |
| 3 | 2024-02-02 | 450.00 | 1250.00 |
| 4 | 2024-02-03 | 800.00 | 2050.00 |
| 5 | 2024-02-03 | 200.00 | 2250.00 |
Each row gets its own distinct running total. ROWS doesn't care about value equality — it counts positions.
Warning
The default RANGE behavior is intentional and correct for certain use cases (like month-to-date totals where you want all same-date rows to reflect the full day's activity). But it's the number one source of "my running total looks wrong" bugs in production SQL. When in doubt — especially for order-level or row-level calculations — be explicit with ROWS BETWEEN.
Don't dismiss RANGE as just a footgun. It's genuinely the right tool for certain patterns.
Month-to-date totals: Suppose you're building a financial dashboard and you want to show each day's total alongside the cumulative total from the beginning of that month. Using RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW with ORDER BY on the date means every row on the same date shows the same cumulative — which is correct if your fact table stores daily aggregates and you need "as of this date" figures.
Value-relative lookbacks: RANGE becomes powerful when combined with numeric ORDER BY columns and numeric bounds. For example, if you have a table of products with prices and you want each product's average price within ±$10 of its own price:
SELECT
product_name,
price,
AVG(price) OVER (
ORDER BY price
RANGE BETWEEN 10 PRECEDING AND 10 FOLLOWING
) AS local_price_avg
FROM products;
Here, 10 PRECEDING doesn't mean "10 rows back" — it means "where price >= current_price - 10." This is an elegant way to do value-range aggregations without a self-join. For more sophisticated ways to avoid self-joins in SQL, see Advanced JOIN Patterns: Self Joins, Anti Joins, and Semi Joins.
Note
The numeric RANGE syntax (e.g., RANGE BETWEEN 10 PRECEDING AND 10 FOLLOWING) works in PostgreSQL, SQL Server, and most modern databases, but the ORDER BY column must be numeric or a date/interval type, not a string. Check your database's documentation for exact interval syntax when using dates.
Partitions and frames work together, not instead of each other. PARTITION BY divides rows into independent groups; the frame then operates within each partition independently.
Here's a practical example from an e-commerce context: a 7-day rolling revenue total, calculated separately for each product category.
SELECT
sale_date,
category,
daily_revenue,
SUM(daily_revenue) OVER (
PARTITION BY category
ORDER BY sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS rolling_7day_revenue
FROM category_daily_sales
ORDER BY category, sale_date;
The frame resets at every partition boundary. When SQL moves from the last row of "Electronics" to the first row of "Clothing," it treats that first Clothing row as if it has zero preceding rows — the lookback doesn't bleed across categories.
This is exactly the behavior you want for most business metrics. A 7-day rolling average for Clothing shouldn't include Electronics data just because those rows happen to be physically adjacent in the result set.
Tip
When you're building production analytics with rolling windows and partitions, organizing your query with Common Table Expressions (CTEs) makes the logic much easier to read and debug. You can build the base aggregation in one CTE and apply the window function in the next.
So far, all our frames have looked backward. But you can also look forward using FOLLOWING bounds — useful for lead indicators or centered moving averages.
A centered 5-day average looks two days back and two days forward:
SELECT
traffic_date,
page_views,
ROUND(
AVG(page_views) OVER (
ORDER BY traffic_date
ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING
),
1
) AS centered_5day_avg
FROM daily_traffic
ORDER BY traffic_date;
The first two rows and the last two rows will use partial frames (fewer than 5 rows available), but the middle rows get the full centered window. This is a common smoothing technique in time-series analysis.
You can also build a pure forward-looking window:
SUM(projected_revenue) OVER (
ORDER BY forecast_month
ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING
) AS next_3_month_forecast
This would sum the current month plus the next two — useful for rolling forecast reports.
Work through these three problems using the sales_orders table from earlier in this lesson. Add these additional rows first:
INSERT INTO sales_orders VALUES
(6, '2024-02-04', 950.00),
(7, '2024-02-05', 125.00),
(8, '2024-02-05', 375.00),
(9, '2024-02-06', 600.00),
(10, '2024-02-07', 1100.00);
Exercise 1: Write a query that returns each order with a running total of amount using ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Verify that every order gets a unique cumulative total.
Exercise 2: Modify your query to instead use RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW (or just remove the frame clause, since that's the default). Compare the results for order_id 7 and 8 (both on February 5th). Do you see the same number for both rows? Why?
Exercise 3: Write a 3-day rolling average of amount, ordered by order_date. Use ROWS BETWEEN 2 PRECEDING AND CURRENT ROW. What happens for the two rows on February 5th — which three rows does each of them look back at? Run the query and confirm your mental model matches the output.
Mistake 1: Forgetting that the default frame is RANGE, not ROWS
When you write SUM(...) OVER (ORDER BY some_date) without an explicit frame clause, you get RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. On unique values, this looks identical to a ROWS frame — which is exactly why the bug hides until you hit duplicate dates in production. Always write your frame clause explicitly.
Mistake 2: Putting ROWS/RANGE in the wrong position
The frame clause goes after ORDER BY, not before it and not inside PARTITION BY. This is correct:
SUM(amount) OVER (PARTITION BY category ORDER BY sale_date ROWS BETWEEN ...)
This is wrong (and will cause a syntax error in most databases):
SUM(amount) OVER (ROWS BETWEEN ... PARTITION BY category ORDER BY sale_date)
Mistake 3: Using a frame clause without ORDER BY
A frame clause requires ORDER BY inside the OVER() clause. Without an ORDER BY, there's no concept of "preceding" or "following" — the rows have no defined order relative to each other. Most databases will throw an error if you try.
Mistake 4: Expecting RANGE with a date column to do date arithmetic automatically
RANGE BETWEEN 7 PRECEDING AND CURRENT ROW with a date ORDER BY column does not mean "the last 7 days." It means "7 date units preceding" — which in most databases works as expected for integer-like date arithmetic, but interval syntax varies. In PostgreSQL, you'd write RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW. In SQL Server, RANGE only supports UNBOUNDED and CURRENT ROW as bounds (not numeric offsets), so you'd need ROWS for a numeric lookback instead. Always test your frame logic against data with gaps in dates to make sure it's doing what you think.
Warning
If your date column has gaps (weekends, holidays, missing data), a ROWS BETWEEN 6 PRECEDING AND CURRENT ROW frame will always include exactly 7 physical rows — which may span more or fewer than 7 calendar days. If you need "last 7 calendar days regardless of gaps," you need a different approach using a date dimension table or a correlated subquery. For deeper strategies on this exact problem, see SQL for Data Analysis: Cohort Analysis, Funnels, and Retention - Complete Guide.
Mistake 5: Mixing up UNBOUNDED FOLLOWING and CURRENT ROW for a full-partition total
If you want every row to show the partition's grand total (not a running total, but the same total on every row), the frame is ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. Ending at CURRENT ROW gives you a running total, not a full total. This is a subtle but important distinction when building percentage-of-total calculations.
Window frame clauses are what separate a vague "window function user" from someone who actually controls their calculations. Here's what you now know:
ORDER BY has a frame, defaulting to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWROWS mode counts physical rows; RANGE mode counts value-based positions and groups ties togetherROWS is almost always the right choiceRANGE with numeric bounds lets you do value-relative aggregations without self-joinsPARTITION BY and frame clauses are complementary — the frame resets at every partition boundaryFrom here, your natural next step is to explore the full depth of frame options including the GROUPS mode and advanced performance implications in Advanced Window Frame Specifications: ROWS, RANGE, and GROUPS Clauses for Precise Rolling Calculations. You'll also find that combining explicit frames with Statistical Aggregations in SQL: PERCENTILE, MEDIAN, STDDEV, and Variance Functions for Data Analysis opens up a lot of sophisticated reporting patterns that are surprisingly compact to write.
Window functions with precise frame control are one of those rare SQL techniques where the more precisely you express your intent, the cleaner and faster your queries become. You're now equipped to do exactly that.
Advanced SQL Queries