RANGE Value Offsets Cover Peer Rows

Value-offset RANGE frames measure distance on the sort key itself, so rows within 5 units of the current value share one frame.

SqlData Fetching

Code

snippet
-- RANGE 的偏移量作用在排序键的数值上,不是行数:
-- 与当前值相差不超过 5 的行(含等值 peer 行)共享同一个帧
-- 数值偏移配数值排序列;时间列配 INTERVAL 偏移,两者同一语义
WITH bids (lot, price) AS (
    VALUES (1, 100), (1, 102), (1, 106), (1, 110)
)
SELECT
    lot,
    price,
    SUM(price) OVER (
        PARTITION BY lot
        ORDER BY price
        RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING
    ) AS cluster_sum,
    COUNT(*) OVER (
        PARTITION BY lot
        ORDER BY price
        RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING
    ) AS cluster_rows
FROM bids
ORDER BY price;

-- price=100 的帧覆盖 [95,105] → 含 100/102,sum=202
-- price=106 的帧覆盖 [101,111] → 含 102/106/110,sum=318

Offsets on the value, not the row count

RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING measures distance on the sort key: a row’s frame covers every row whose price lies within 5 of its own — peers at the same price always share the frame.

The two clusters

price=100 covers [95,105] and sums 100 + 102 = 202 with 2 rows; price=106 covers [101,111] and sums 102 + 106 + 110 = 318 with 3 rows. The COUNT(*) window makes the membership visible next to the sums.

Numeric or interval

The offset type follows the sort column: numeric offsets for numeric keys, INTERVAL for timestamps — the same value-distance semantics on both.

Interactive Tools for This Topic

FAQ

How does RANGE differ from ROWS for ties?
RANGE puts equal sort-key rows (peers) in the same frame by definition; ROWS counts physical rows and can split a tie across frames.
What offset type does a timestamp sort key need?
INTERVAL — the offset must match the sort column's type, which keeps the same value-distance semantics for time keys.