SQL Window Frames

The third piece of a window definition — exactly which rows within the partition are visible.

What & Why

A window frame narrows an ordered partition with ROWS or RANGE boundaries such as unbounded preceding and current row. Frames distinguish a running metric from a moving metric and prevent surprising LAST_VALUE or cumulative results.

See How It Works

BUSINESS QUESTION

Calculate 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 — rolling seven-row DAU sum
date_daydaurolling_7_row_dau
2024-04-0112401240
2024-04-0213152555
2024-04-0312883843
2024-04-0413925235

Only four source rows exist, so every frame begins at the first representative day.

Advanced business practice

Sign up free to try it on a real business scenario