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.
Code
-- 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=318Offsets 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.