Advanced Window Frames, NTILE, and LAST_VALUE
Most window-function bugs are frame bugs. If you have ever seen a running total that includes the wrong rows or a LAST_VALUE that behaves like a neighbor, the cause is almost always the implicit frame.
- ROWS vs RANGE vs GROUPS â three ways to define which rows belong to the frame
- The default frame trap â what OVER (ORDER BY ...) actually computes without a frame
- NTILE, FIRST_VALUE, NTH_VALUE â distribution and value functions with sharp edges
- Patterns that pay â sessionization, cumulative revenue, and quartile assignment Control the frame explicitly and half of your window problems disappear.
Prerequisites
- !Comfort with ROW_NUMBER, RANK, and DENSE_RANK
- !Experience writing OVER (PARTITION BY ... ORDER BY ...)
- !Basic knowledge of aggregate functions such as SUM and AVG
What You'll Learn
- 1State the default frame for aggregate window functions and why it surprises people
- 2Choose between ROWS, RANGE, and GROUPS frames for a given question
- 3Use NTILE to assign balanced buckets and understand its remainder distribution
- 4Fix the LAST_VALUE / NTH_VALUE ordering trap with explicit frames
The Frame Is the Missing Half of OVER
Every window function call has two parts: the OVER clause that defines the window (partitioning and ordering) and, for aggregate and value functions, the frame â the subset of the partition that the function actually sees. Ranking functions like ROW_NUMBER ignore frames entirely. Aggregate functions like SUM, AVG, MIN, MAX, and value functions like FIRST_VALUE and LAST_VALUE do not.
The default frame depends on whether ORDER BY appears inside OVER:
OVER clause | Default frame | Practical effect |
|---|---|---|
OVER (PARTITION BY g) | Entire partition | Every row sees the whole group |
OVER (PARTITION BY g ORDER BY x) | RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW | Running total; ties on x share the same accumulated value |
OVER (PARTITION BY g ORDER BY x ROWS BETWEEN ...) | Your explicit frame | Precise control, no surprises |
Because the ORDER BY default uses RANGE rather than ROWS, rows with equal sort keys form a peer group and all receive the same cumulative value. If you ordered by a column with heavy ties â a status, a day without times, a low-cardinality score â your "running" total will jump in lumps and then appear correct only by accident.
-- The classic surprise: ties in ORDER BY change the running total
WITH daily AS (
SELECT DATE '2024-03-04' AS d, 120 AS revenue UNION ALL
SELECT DATE '2024-03-05', 80 UNION ALL
SELECT DATE '2024-03-05', 55 UNION ALL -- same day: peer of the previous row
SELECT DATE '2024-03-06', 200 UNION ALL
SELECT DATE '2024-03-07', 90
)
SELECT
d,
revenue,
SUM(revenue) OVER (ORDER BY d) AS running_default, -- RANGE: peers share value
SUM(revenue) OVER (ORDER BY d ROWS UNBOUNDED PRECEDING) AS running_rows, -- one row at a time
SUM(revenue) OVER (ORDER BY d RANGE UNBOUNDED PRECEDING) AS running_range
FROM daily;
-- running_default gives both 2024-03-05 rows the same 255.
-- running_rows gives 200 then 255 â the row-by-row accumulation most people expect.
When you want a true row-by-row accumulation, say ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW explicitly. When you genuinely want peers treated together â for example, cumulative revenue up to and including everything on that date â RANGE is exactly right. The rule is to write the intent, not to inherit a default.
ROWS, RANGE, and GROUPS Side by Side
All three frame types share the same grammar skeleton: a start bound, the keyword AND, and an end bound. They differ in how they interpret rows that tie on the sort key.
| Frame type | Bound meaning | Example | Typical use |
|---|---|---|---|
| ROWS | Physical offset in the sorted partition | ROWS BETWEEN 2 PRECEDING AND CURRENT ROW | Moving averages over an ordered event stream |
| RANGE | Logical peer group based on sort-key values | RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW | Cumulative metrics up to a date, including ties |
| GROUPS | Offset in peer groups (PostgreSQL 11+) | GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW | Compare each row to the previous distinct value |
RANGE frames can take value offsets only when the sort key is numeric or temporal: RANGE BETWEEN 100 PRECEDING AND CURRENT ROW means values within 100 of the current sort key. GROUPS sits between the two: GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW includes the previous peer group, no matter how many rows it contains.
The EXCLUDE clause fine-tunes which rows inside the frame boundary are removed: EXCLUDE CURRENT ROW, EXCLUDE GROUP (the peer group of the current row), EXCLUDE TIES, or EXCLUDE NO OTHERS (the default). It is niche, but it solves problems like "cumulative sum excluding the current row" without a separate self-join.
-- Session-style moving window with EXCLUDE: average excluding the current event
SELECT
event_id,
user_id,
event_at,
revenue,
AVG(revenue) OVER (
PARTITION BY user_id
ORDER BY event_at
ROWS BETWEEN 3 PRECEDING AND 1 FOLLOWING
EXCLUDE CURRENT ROW
) AS avg_neighbors
FROM events;
NTILE: Balanced Buckets with a Defined Remainder Rule
NTILE(n) splits each partition into n buckets as evenly as possible and returns the bucket number, starting at 1. Unlike RANK, which assigns the same value to tied rows, NTILE always assigns every row a bucket â ties are broken arbitrarily by the engine following the ORDER BY inside the window.
When the row count does not divide evenly, the extra rows go to the earliest buckets: each of the first r buckets gets one additional row, where r is the remainder. So with 10 rows and NTILE(3), the buckets contain 4, 3, and 3 rows. This matters when bucket sizes feed downstream math â a "top third" that quietly contains 40 percent of rows can skew a per-bucket average.
-- Quartiles of customer lifetime value with documented bucket sizes
WITH clv AS (
SELECT
c.customer_id,
c.region,
SUM(o.total) AS lifetime_value
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.region
),
quartiled AS (
SELECT
customer_id,
region,
lifetime_value,
NTILE(4) OVER (PARTITION BY region ORDER BY lifetime_value DESC) AS quartile,
COUNT(*) OVER (PARTITION BY region) AS customers_in_region
FROM clv
)
SELECT
quartile,
customers_in_region,
COUNT(*) AS rows_in_quartile,
ROUND(AVG(lifetime_value), 2) AS avg_clv,
MIN(lifetime_value) AS min_clv,
MAX(lifetime_value) AS max_clv
FROM quartiled
GROUP BY quartile, customers_in_region
ORDER BY quartile;
Use NTILE for percentile-style reporting and dashboard segmentation. Prefer RANK or DENSE_RANK when ties must receive the same label, and PERCENT_RANK() or CUME_DIST() when you need a continuous position in [0, 1] rather than discrete buckets.
FIRST_VALUE, LAST_VALUE, and the Ordering Trap
Value functions return an expression evaluated at a specific row of the frame. FIRST_VALUE(expr) takes the first row, LAST_VALUE(expr) the last, and NTH_VALUE(expr, n) the n-th (PostgreSQL numbers from 1; some engines start at 0 â check yours).
The trap: with the default frame ending at CURRENT ROW, LAST_VALUE always sees the current row as its last row â so it returns the current row's value and looks like a useless column. The fix is an explicit frame that extends to the end of the partition: ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.
-- FIRST_VALUE and LAST_VALUE with correct frames: first and latest order per customer
SELECT
c.customer_id,
c.first_name,
o.order_id,
o.order_date,
o.total,
FIRST_VALUE(o.order_id) OVER (
PARTITION BY c.customer_id
ORDER BY o.order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS first_order_id,
LAST_VALUE(o.order_id) OVER (
PARTITION BY c.customer_id
ORDER BY o.order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS latest_order_id,
NTH_VALUE(o.total, 2) OVER (
PARTITION BY c.customer_id
ORDER BY o.order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS second_order_total
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id;
A second subtlety: ordering ties. If two orders share a timestamp, which one counts as "latest" is arbitrary unless you add a tiebreaker to ORDER BY â typically the primary key. Always order value functions by a full sort key: ORDER BY o.order_date, o.order_id.
Mixing Frame Functions with Whole-Partition Context
A frequent reporting need is to show each row alongside both its local window context and its partition-wide context: the trailing three-order average next to the customer's lifetime total. You can mix frame-limited aggregates and frame-free aggregates in one SELECT, because each OVER clause is evaluated independently â the frame belongs to the function call, not to the row.
-- Local frame context beside partition-wide context in one pass
SELECT
o.order_id,
o.customer_id,
o.order_date,
o.total,
AVG(o.total) OVER (
PARTITION BY o.customer_id
ORDER BY o.order_date, o.order_id
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS avg_last_3_orders,
SUM(o.total) OVER (PARTITION BY o.customer_id) AS customer_lifetime,
ROUND(100.0 * o.total
/ NULLIF(SUM(o.total) OVER (PARTITION BY o.customer_id), 0), 1) AS pct_of_lifetime
FROM orders o
WHERE o.status = 'paid';
The pattern generalizes: put the narrow frame in one function, the unframed whole-partition aggregate in another, and let the outer query compare them. Just remember that every additional OVER clause adds another sort or hash partitioning operation to the plan; on very wide partitions, prefer computing the partition-wide aggregate once in a prior CTE and joining it back instead of repeating heavy aggregates per row.
Patterns Worth Internalizing
Three frame-based patterns recur in production analytics.
Sessionization and gap detection. Mark a new session whenever the time since the previous event exceeds a threshold, using LAG to compare timestamps, then sum the markers to form a session id. The frame controls how far back you look; LAG(x, 1, default) OVER (...) supplies a default for the first row.
Cumulative metrics with correct peer semantics. Decide deliberately between RANGE (include ties) and ROWS (strictly incremental). For financial ledgers, ROWS with a full tiebreaker is safer. For calendar reporting, RANGE over a date is usually what the business means.
Rolling statistics. Moving averages and medians use bounded frames: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW for a seven-point average. For medians, combine a frame with an ordered value function, or compute in the outer query after filtering the frame â engines do not offer a direct MEDIAN window function in all dialects.
Common Mistakes
Relying on the implicit default frame with ORDER BY in OVER
Fix: Write the frame explicitly: ROWS for row-by-row, RANGE for peer-inclusive
Calling LAST_VALUE without extending the frame to UNBOUNDED FOLLOWING
Fix: Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or use a different pattern
Ordering value functions by a non-unique column
Fix: Append a unique tiebreaker such as the primary key to OVER (... ORDER BY)
Expecting NTILE buckets to be identical in size
Fix: Remember the remainder rule: the first r buckets each gain one row
Applying COUNT(*) OVER () style whole-partition aggregates inside a frame-limited function call
Fix: Mixing frame-sensitive and frame-insensitive functions in one SELECT is fine, but understand which defaults apply to each
Best Practices
- Always specify frames explicitly in code that other engineers will read
- Document whether RANGE or ROWS semantics the business wants for cumulative metrics
- Add unique tiebreakers to every OVER (... ORDER BY) used with value functions
- Sanity-check window results with a small hand-computed sample before shipping
- Prefer NTILE for dashboards and RANK when ties must share a label
Interview Questions
Q1: What is the default frame when OVER includes ORDER BY?
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Tied sort keys form a peer group and receive identical cumulative values, which often surprises developers expecting a row-by-row running total.
Q2: Why does LAST_VALUE seem to return the current row?
Its default frame ends at CURRENT ROW, so the last row of the frame is always the current row. Extend the frame with UNBOUNDED FOLLOWING, and add a unique tiebreaker to the ORDER BY.
Q3: How does NTILE divide 10 rows into 3 buckets?
The first remainder buckets get the extra rows: sizes are 4, 3, and 3, assigned in the order of the window's ORDER BY.
Key Takeaways
- Frames matter only for aggregate and value functions, not ranking functions
- The implicit RANGE default treats tied sort keys as one peer group
- ROWS gives row-precise frames; RANGE uses sort-key values; GROUPS offsets by peer groups
- NTILE always assigns rows, breaking ties arbitrarily and front-loading remainders
- FIRST_VALUE, LAST_VALUE, and NTH_VALUE need explicit frames and unique sort keys