Learn SQL/Advanced/Window Functions/SQL Moving Window Frames

SQL Moving Window Frames

A frame that travels WITH the current row, instead of anchoring at the start of the partition.

What & Why

Replace UNBOUNDED PRECEDING with a fixed number, and the frame stops growing — it slides forward with each row instead, always covering the same span. This is the mechanism behind every moving average.

See How It Works

BUSINESS QUESTION

Growth wants a seven-row rolling active-user total.

date_daydaunew_usersreturning_users
2024-04-0112401801060
2024-04-0213152051110
2024-04-0312881641124
2024-04-0413922211171
EXAMPLE QUERY
SELECT
  date_day,
  dau,
  SUM(dau) OVER (ORDER BY date_day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS rolling_7_row_dau
FROM growth.daily_active_users
ORDER BY date_day;
RESULT — moving DAU sum
date_daydaurolling_7_row_dau
2024-04-0112401240
2024-04-0213152555
2024-04-0312883843
2024-04-0413925235

The trailing frame expands across the four available representative rows.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario