← Back to SQL, page 15

sql-0293 · Hard senior

How does a GROUPS frame differ from ROWS when the ORDER BY column has duplicates?

ROWS BETWEEN 1 PRECEDING AND CURRENT ROW counts physical rows, so it may include only part of a group of equal values. GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW counts peer groups, so it includes the whole current group and the whole previous group. SQLite 3.28+ and PostgreSQL 11+ support GROUPS.

Full answer
sql
WITH t(id, day, amount) AS (VALUES (1, 1, 10), (2, 2, 5), (3, 2, 7), (4, 3, 1))
SELECT id, day, amount,
       SUM(amount) OVER (ORDER BY day, id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS rows_sum,
       SUM(amount) OVER (ORDER BY day GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW) AS groups_sum
FROM t ORDER BY id;
iddayamountrows_sumgroups_sum
11101010
2251522
3271222
431813

Day 2 has two rows. With ROWS, the second day-2 row sums itself and the row just before it (the other day-2 row). With GROUPS, every day-2 row sums all of day 2 plus all of day 1, because the frame is measured in groups of equal day values.

GROUPS is the natural choice for "this day and the previous day" when days can have several rows and every day is present. If days can be missing, use RANGE with a numeric offset on a day number instead, since GROUPS also ignores gaps.

sql
WITH t(id, day, amount) AS (VALUES (1, 1, 10), (2, 2, 5), (3, 2, 7), (4, 3, 1))
SELECT id, day, amount,
       SUM(amount) OVER (ORDER BY day, id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS rows_sum,
       SUM(amount) OVER (ORDER BY day GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW) AS groups_sum
FROM t ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • ROWS counts physical rows
  • GROUPS counts peer groups of equal ORDER BY values
  • GROUPS includes whole groups at each end
  • Supported in SQLite 3.28+ and PostgreSQL 11+

Common mistakes

  • Using ROWS for per-day windows when days have several rows
  • Assuming GROUPS skips missing days correctly

Follow-ups

  • How would RANGE BETWEEN 1 PRECEDING work here?
  • What does EXCLUDE TIES do?

Tips

  • Point to a duplicate-day row