Learn SQL/Advanced/Window Functions/SQL Rolling Average

SQL Rolling Average

Usually means a TRAILING average — only rows before and including the current one, not centered.

What & Why

"Rolling average" often specifically implies a trailing window — the current row plus a fixed number of rows before it, never after. This is the natural choice whenever "after" doesn't exist yet, like a live dashboard showing trailing performance.

See How It Works

BUSINESS QUESTION

Growth wants a seven-observation rolling average of daily active users.

date_daydaunew_usersreturning_users
2024-04-0112401801060
2024-04-0213152051110
2024-04-0312881641124
2024-04-0413922211171
EXAMPLE QUERY
SELECT
  date_day,
  dau,
  ROUND(AVG(dau) OVER (ORDER BY date_day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 2) AS rolling_7_row_avg
FROM growth.daily_active_users
ORDER BY date_day;
RESULT — rolling DAU average
date_daydaurolling_7_row_avg
2024-04-0112401240.00
2024-04-0213151277.50
2024-04-0312881281.00
2024-04-0413921308.75

The seven-row frame uses all rows available so far in this four-row sample.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario