The idea · Lab 3.3.7ROWS BETWEEN n PRECEDING AND CURRENT ROW counts a fixed number of physical rows, regardless of what values those rows actually hold. For a daily rolling average, that is a subtle trap: if one day's data is missing entirely — no row at all, not a zero — a "7-row" window silently reaches back an extra calendar day to find its 7th row, quietly computing an 8-calendar-day average while still being labeled a 7-day one. RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW fixes this by defining the frame in terms of the actual ORDER BY values — real calendar dates — rather than row positions, so a missing day simply shrinks the window to whatever days genuinely exist within the last 6, instead of silently reaching further back. GROUPS BETWEEN extends the same idea one step further, framing by how many distinct peer groups (rows sharing an identical ORDER BY value) precede the current one, rather than by rows or by a range of values.
Two more tools close out this block's tour of solving analytics problems inside the database: crosstab() genuinely pivots rows into columns for report-style output, and TABLESAMPLE SYSTEM trades perfect accuracy for real, measured speed on massive tables — both honest tradeoffs, both measured directly rather than assumed.
ROWS BETWEEN vs RANGE BETWEEN, Across a Real Gap
With January 10th deliberately missing from the data:
SELECT sale_date, revenue,
sum(revenue) OVER (ORDER BY sale_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS rows_7,
sum(revenue) OVER (ORDER BY sale_date RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW) AS range_7
FROM sql_sales ORDER BY sale_date;
sale_date | revenue | rows_7 | range_7
------------+---------+--------+---------
2025-01-09 | 556 | 3745 | 3745
2025-01-11 | 570 | 3801 | 3280
For January 11th, rows_7 reaches back to include January 5th through 9th plus the 11th — 7 physical rows, but 7 calendar days apart from a gap, silently including one extra day of real data than a "7-day" label implies. range_7 only includes rows whose actual date falls within the last 6 calendar days of the 11th — January 5th through 9th and the 11th, but correctly recognizing only 6 of those days actually have data, summing exactly what a genuine 7-calendar-day window should.
GROUPS BETWEEN: Framing by Peer Groups
SELECT id, grp, val, sum(val) OVER (ORDER BY grp GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW) AS groups_sum
FROM sql_grp_demo ORDER BY id;
id | grp | val | groups_sum
----+-----+-----+------------
1 | 1 | 10 | 30
4 | 3 | 40 | 180
5 | 3 | 50 | 180
6 | 3 | 60 | 180
Rows 4, 5, and 6 all share grp = 3 and are treated as a single peer group: their frame is "this whole peer group plus the one preceding peer group" (grp 2's single row, value 30), giving 40+50+60+30 = 180 for all three, identically — framing by group membership, not by row count or value range.
crosstab(): Rows Into Columns
SELECT * FROM crosstab(
'SELECT region, quarter, revenue FROM sql_region_sales ORDER BY 1,2',
'SELECT DISTINCT quarter FROM sql_region_sales ORDER BY 1'
) AS ct(region text, q1 numeric, q2 numeric, q3 numeric, q4 numeric);
region | q1 | q2 | q3 | q4
--------+------+------+------+------
east | 1000 | 1100 | 1200 | 1300
west | 900 | 950 | 1000 | 1050
A genuine pivot: one row per region, one column per quarter — the exact matrix shape a spreadsheet-style report needs, built entirely in SQL.
TABLESAMPLE SYSTEM: Speed and Its Real Cost
EXPLAIN (ANALYZE, TIMING OFF) SELECT avg(val) FROM sql_bigsample; -- 1985.255 ms, full scan
EXPLAIN (ANALYZE, TIMING OFF) SELECT avg(val) FROM sql_bigsample TABLESAMPLE SYSTEM(1); -- 43.243 ms, ~1% sampled
About 46 times faster on 500,000 rows. The tradeoff, measured directly:
SELECT round(avg(val),3) FROM sql_bigsample; -- true_avg: 500.595
SELECT round(avg(val),3) FROM sql_bigsample TABLESAMPLE SYSTEM(1); -- sampled_avg: 499.910
Within roughly 0.14% of the true average — a real, honest error margin in exchange for a dramatic speedup, appropriate for a dashboard estimate, inappropriate for a number that has to be exactly correct (a financial total, a billing calculation).
Key concepts
RANGE BETWEEN INTERVAL ... PRECEDING
A window frame defined by actual ORDER BY values within a given range, rather than by counting physical rows. For a date-ordered window, RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW includes every row whose date genuinely falls within that 6-day span — correctly including fewer rows when data is missing, unlike ROWS BETWEEN, which always counts exactly the requested number of physical rows regardless of what dates they actually represent.
TABLESAMPLE SYSTEM
A table sampling method that selects entire storage pages at random (approximately the requested percentage of them) rather than sampling individual rows, making it very fast since it can skip most of the table entirely — at the cost of a specific kind of imprecision: if rows within a page are correlated (all inserted together, sharing some property), SYSTEM sampling can be less representative than TABLESAMPLE BERNOULLI, which samples individual rows at the cost of still reading every page.
What to remember
- ROWS BETWEEN counts physical rows regardless of their actual values; RANGE BETWEEN counts by real value distance, which is what correctly handles a missing day in a "calendar days" window
- GROUPS BETWEEN frames by distinct peer groups (tied ORDER BY values counted as one unit), a third distinct framing option alongside ROWS and RANGE
- crosstab() from the tablefunc extension genuinely reshapes rows into a column-per-category pivot, entirely inside SQL
- TABLESAMPLE SYSTEM trades a small, genuinely measurable error margin for a dramatic, genuinely measured speedup — appropriate for estimates, not for figures that must be exactly correct
- TABLESAMPLE SYSTEM samples whole pages (fast, with a real clustering-bias risk); TABLESAMPLE BERNOULLI samples individual rows (unbiased by clustering, but far slower)