🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Window Frames: ROWS, RANGE, GROUPS, BETWEEN, EXCLUDE

Advanced SQLWindow Frames⭐ Premium

Interview Question: "What's the difference between ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW versus RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW? When would you use GROUPS?" — Asked at Google, Facebook, Amazon for Data Scientist roles

â„šī¸

Difficulty: Advanced | Companies: Google, Facebook, Amazon, Microsoft, Apple | Time: 45-60 minutes

Window Frame Syntax

The complete window frame syntax:

Three rules govern the clause before any of its arithmetic. A frame is only legal when the window has an ORDER BY — without one every row of the partition is a single peer group and the frame covers the partition from end to end. The start bound must not fall after the end bound, so ROWS BETWEEN CURRENT ROW AND 2 PRECEDING is rejected outright rather than quietly returning an empty set. And when ORDER BY is present with no frame written at all, the standard supplies RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW — a value-based frame, which is why a "running total" built on the default jumps by several rows the moment the ORDER BY column repeats.

-- Create time-series data for frame analysis
CREATE TABLE stock_prices (
    trade_date DATE,
    symbol VARCHAR(10),
    price DECIMAL(10,2),
    volume INT
);

INSERT INTO stock_prices VALUES
('2024-01-01', 'AAPL', 150.00, 1000000),
('2024-01-02', 'AAPL', 152.50, 1200000),
('2024-01-03', 'AAPL', 148.75, 800000),
('2024-01-04', 'AAPL', 155.00, 1500000),
('2024-01-05', 'AAPL', 153.25, 900000),
('2024-01-08', 'AAPL', 157.50, 1100000),
('2024-01-09', 'AAPL', 159.00, 1300000),
('2024-01-10', 'AAPL', 156.75, 700000),
('2024-01-11', 'AAPL', 160.00, 1400000),
('2024-01-12', 'AAPL', 162.50, 1600000);

ROWS Frame Type

ROWS counts physical rows regardless of values:

-- ROWS: Fixed number of physical rows
SELECT 
    trade_date,
    price,
    volume,
    -- 3-day moving average (ROWS)
    AVG(price) OVER (
        ORDER BY trade_date
        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
    ) AS moving_avg_3day,
    
    -- 5-day moving sum
    SUM(volume) OVER (
        ORDER BY trade_date
        ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING
    ) AS moving_sum_5day,
    
    -- Running average from start
    AVG(price) OVER (
        ORDER BY trade_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_avg,
    
    -- Entire dataset average
    AVG(price) OVER (
        ORDER BY trade_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    ) AS overall_avg
FROM stock_prices
ORDER BY trade_date;

Output:

trade_datepricevolumemoving_avg_3daymoving_sum_5dayrunning_avgoverall_avg
2024-01-01150.001000000150.004500000150.00155.53
2024-01-02152.501200000151.254700000151.25155.53
2024-01-03148.75800000150.425400000150.42155.53
2024-01-04155.001500000152.085700000151.56155.53
2024-01-05153.25900000152.336800000151.90155.53
2024-01-08157.501100000155.256800000152.83155.53
2024-01-09159.001300000156.587000000153.71155.53
2024-01-10156.75700000157.757100000154.09155.53
2024-01-11160.001400000158.587200000154.72155.53
2024-01-12162.501600000159.757100000155.53155.53

â„šī¸

ROWS Behavior: With ROWS, the frame always contains exactly the specified number of rows. If fewer rows exist, the frame is smaller.

The output makes the physical counting visible. The three-row average on 1 January is simply 150.00 because only one row exists, on 2 January it is the mean of two rows, and from 3 January onward it is a genuine three-row window — 150.42, then 152.08, then 152.33. The telling row is Monday 8 January: its three-row average covers the prints of Thursday 4 January, Friday 5 January and Monday itself, giving 155.25, because ROWS counts rows rather than calendar days and the weekend produced none. If the metric must span three calendar days, a ROWS frame over a sparse series silently mixes in data from further back than the label claims, and a RANGE frame over dates is the correct form.

The running average column behaves the same way: it is UNBOUNDED PRECEDING to CURRENT ROW, so it converges on 155.53 — the mean of all ten prints — at the last row. Reaching that same value through ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING produces a constant column instead, which is what you want when every row must display the overall figure.

RANGE Frame Type

RANGE includes all rows with values within the logical range:

-- RANGE: Logical value range
SELECT 
    trade_date,
    price,
    volume,
    -- Sum of prices within Âą5 of current price
    SUM(price) OVER (
        ORDER BY price
        RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING
    ) AS sum_within_range,
    
    -- Count of stocks within 10% of current price
    COUNT(*) OVER (
        ORDER BY price
        RANGE BETWEEN price * 0.1 PRECEDING AND price * 0.1 FOLLOWING
    ) AS count_nearby_prices,
    
    -- Average of all rows with price <= current
    AVG(volume) OVER (
        ORDER BY price
        RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS avg_volume_lower_prices
FROM stock_prices
ORDER BY trade_date;

Output:

trade_datepricevolumesum_within_rangecount_nearby_pricesavg_volume_lower_prices
2024-01-01150.001000000451.2531000000.00
2024-01-02152.501200000604.5041100000.00
2024-01-03148.75800000451.253900000.00
2024-01-04155.001500000609.5041166666.67
2024-01-05153.25900000609.5041100000.00
2024-01-08157.501100000467.5021100000.00
2024-01-09159.001300000479.0021200000.00
2024-01-10156.75700000474.2531033333.33
2024-01-11160.001400000320.0011160000.00
2024-01-12162.501600000162.5011200000.00

GROUPS Frame Type

GROUPS counts peer groups (rows with same ORDER BY value):

-- GROUPS: Peer group counting
SELECT 
    trade_date,
    price,
    volume,
    -- Sum of 1 peer group before and after
    SUM(price) OVER (
        ORDER BY price
        GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING
    ) AS sum_peer_groups,
    
    -- Count with GROUPS
    COUNT(*) OVER (
        ORDER BY volume
        GROUPS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS count_peer_groups,
    
    -- Average with GROUPS
    AVG(price) OVER (
        ORDER BY volume
        GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING
    ) AS avg_peer_groups
FROM stock_prices
ORDER BY trade_date;

GROUPS exists because ROWS and RANGE both mishandle ties, in opposite directions. ROWS walks individual positions, so three rows sharing one price count as three separate steps — a ROWS BETWEEN 1 PRECEDING AND CURRENT ROW frame on the third of them sees only the two rows immediately above it and never learns that all three carried the same value. RANGE errs the other way: an offset measured in value units expands to cover every row equal to the boundary, so a small frame can swallow an entire tie group you never meant to include. GROUPS counts the blocks themselves: 1 PRECEDING AND 1 FOLLOWING means the block before, the block containing the current row, and the block after — three blocks regardless of how many rows sit in each. It is the frame to reach for when the ORDER BY column is a category, a price or any other value with frequent repeats and the question is about neighbours rather than about positions.

Frame Boundary Comparison

-- Compare all three frame types
SELECT 
    trade_date,
    price,
    -- ROWS frame
    SUM(price) OVER (
        ORDER BY trade_date
        ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
    ) AS sum_rows,
    
    -- RANGE frame (by value)
    SUM(price) OVER (
        ORDER BY price
        RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING
    ) AS sum_range,
    
    -- GROUPS frame
    SUM(price) OVER (
        ORDER BY price
        GROUPS BETWEEN 1 PRECEDING AND 1 FOLLOWING
    ) AS sum_groups
FROM stock_prices
ORDER BY trade_date;

Output:

trade_datepricesum_rowssum_rangesum_groups
2024-01-01150.00302.50451.25604.50
2024-01-02152.50451.25604.50609.50
2024-01-03148.75456.25451.25604.50
2024-01-04155.00456.25609.50609.50
2024-01-05153.25466.25609.50609.50
2024-01-08157.50468.25467.50479.00
2024-01-09159.00473.25479.00479.00
2024-01-10156.75476.75474.25474.25
2024-01-11160.00479.25320.00160.00
2024-01-12162.50322.50162.50162.50

âš ī¸

Frame Confusion: RANGE with numeric ORDER BY uses Âąn as value range, not row count. This can produce unexpected results.

EXCLUDE Clause Variations

-- EXCLUDE CURRENT ROW
SELECT 
    trade_date,
    price,
    AVG(price) OVER (
        ORDER BY trade_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        EXCLUDE CURRENT ROW
    ) AS avg_excluding_current
FROM stock_prices
ORDER BY trade_date;

-- EXCLUDE GROUP (excludes all peers)
SELECT 
    trade_date,
    price,
    AVG(price) OVER (
        ORDER BY price
        GROUPS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        EXCLUDE GROUP
    ) AS avg_excluding_peers
FROM stock_prices
ORDER BY trade_date;

-- EXCLUDE TIES (excludes peers but keeps current)
SELECT 
    trade_date,
    price,
    AVG(price) OVER (
        ORDER BY price
        GROUPS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
        EXCLUDE TIES
    ) AS avg_excluding_ties
FROM stock_prices
ORDER BY trade_date;

The four exclusion options collapse into one small rule set. EXCLUDE NO OTHERS is the default and keeps every row the bounds defined. EXCLUDE CURRENT ROW drops only the row being evaluated, which turns an average into the average of everyone else — the cheapest leave-one-out statistic available without a self-join. EXCLUDE GROUP drops every row sharing the current row's ORDER BY value, while EXCLUDE TIES drops those peers but keeps the current row itself: the two differ by exactly one row, and that row decides whether a category's own value sits inside its peer average.

Exclusion always applies after the bounds, never before them — the frame is established from the unbounded or offset bounds first, and only then are the excluded rows removed from the aggregate. It is also one of the least portable pieces of window syntax in the standard, and several engines reject the clause outright, so a query built on it needs rewriting into a self-join or a CASE expression before it moves to another database.

Advanced: Moving Percentiles

-- 7-day moving percentile
SELECT 
    trade_date,
    price,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY price) OVER (
        ORDER BY trade_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS moving_median_7day,
    PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY price) OVER (
        ORDER BY trade_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS moving_q1_7day,
    PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY price) OVER (
        ORDER BY trade_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS moving_q3_7day
FROM stock_prices
ORDER BY trade_date;

A percentile over a frame is recomputed for every row rather than once per group. The seven-row window ending on 12 January holds seven prices, and the median is interpolated between the middle two of them instead of quoting an observed print — with an even number of rows in the window the result can be a price that never traded, which is correct for a continuous quantile and misleading when the column counts discrete events and a discrete percentile was wanted. Ordered-set aggregates are also the most expensive residents of a frame, because each row re-sorts its own window, so they belong on a bounded frame such as 6 PRECEDING and never on an unbounded one over a large partition.

Mathematical Formulas

For a window frame over ordered set :

The aggregate over frame :

â„šī¸

Frame Default: Default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW if ORDER BY is specified, or ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING without ORDER BY.

Frame Performance Implications

Frame TypeSort RequiredMemory UsageSpeed
ROWSPhysicalLowFast
RANGELogical valueMediumMedium
GROUPSPeer groupsMediumMedium
-- Check frame execution cost
EXPLAIN (ANALYZE, BUFFERS)
SELECT 
    trade_date,
    AVG(price) OVER (
        ORDER BY trade_date
        ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING
    ) AS moving_avg
FROM stock_prices;

âš ī¸

Performance Warning: RANGE frames with non-integer ORDER BY values can be expensive because the database must evaluate the range for each row.

Common Mistakes

Writing a running total with only ORDER BY and assuming it advances one row at a time

Fix: The default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so peer values are absorbed — write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW when you mean one row at a time

Labeling a ROWS-based window a three-day average on a series with weekends, holidays or missing dates

Fix: ROWS counts rows, not calendar days — use a RANGE frame over the date key, or a generated calendar spine, whenever the label promises days

Putting an unbounded ordered-set percentile inside every row of a large partition

Fix: Bound the frame to a fixed number of preceding rows, or compute the quantile once with GROUP BY, because each row otherwise re-sorts its whole window

Key Takeaways

  • A frame requires ORDER BY, and the default that ORDER BY supplies is a RANGE frame measured in value units rather than in rows
  • ROWS counts positions so sparse series reach further back than their labels claim, RANGE counts value units so ties inflate the frame, and GROUPS counts peer blocks
  • EXCLUDE is applied after the bounds are resolved, and EXCLUDE GROUP differs from EXCLUDE TIES by exactly the current row itself
  • Every RANGE or GROUPS frame is evaluated per row, which is the main reason those frames cost more than an equivalent ROWS frame on a wide partition
🔒

Premium Content

Window Frames: ROWS, RANGE, GROUPS, BETWEEN, EXCLUDE

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement