SQL Window Frames: ROWS, RANGE and GROUPS
Overview
A window frame selects a subset of the current partition for frame-sensitive calculations. ROWS measures positions, RANGE uses ordering values, and GROUPS counts peer groups. For team A the scores are 90, 90, 70, 60 and 50; the two 90s are peers when ordering by points alone.
First example
SELECT id, points, SUM(points) OVER (ORDER BY points DESC, id ROWS UNBOUNDED PRECEDING) AS r, SUM(points) OVER (ORDER BY points DESC RANGE UNBOUNDED PRECEDING) AS v, SUM(points) OVER (ORDER BY points DESC GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW) AS gFROM window_scores WHERE team = 'A' ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 90, 90, 180, 180 ], [ 2, 90, 180, 180, 180 ], [ 3, 70, 250, 250, 250 ], [ 4, 60, 310, 310, 130 ], [ 5, 50, 360, 360, 110 ]]How it works
In the first example, ROWS uses a unique tie-breaker id, so the first 90 contributes alone. RANGE includes both peers immediately; GROUPS with one preceding group includes the current score group and the previous group. In the second example, ascending numeric RANGE includes scores within 10 points below the current score, whereas GROUPS includes the previous distinct score even across a gap. Offset RANGE requires a single ordering expression in both target engines; use a numeric expression in SQLite.
Practical example
SELECT id, SUM(points) OVER (ORDER BY points RANGE BETWEEN 10 PRECEDING AND CURRENT ROW) AS nearby, SUM(points) OVER (ORDER BY points GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW) AS adjacent_groupFROM window_scores WHERE team = 'A' ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 180, 250 ], [ 2, 180, 250 ], [ 3, 130, 130 ], [ 4, 110, 110 ], [ 5, 50, 50 ]]Practice and mistakes
Change the GROUPS offset to zero and predict the result for the two 90-point rows. Common mistake: adding id to the peer-based window and thereby splitting ties. Both examples are executed in SQLite; PostgreSQL 17 supports these frame forms but has not been executed here.