SQL Moving Average

A fixed-size window of AVG instead of SUM — smooths out noise instead of accumulating.

What & Why

A moving average applies AVG over a sliding, fixed-size frame — exactly the moving window frame mechanic from the previous lesson group, now used for its most common real purpose: smoothing out noisy data.

See How It Works

BUSINESS QUESTION

Calculate a three-row moving average of daily active users.

date_daydaunew_usersreturning_users
2024-04-0112401801060
2024-04-0213152051110
2024-04-0312881641124
2024-04-0413922211171
Watch a three-row moving average advanceStep 1 of 4
AVG(dau) ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
date_daydauframe rowsmoving_3_row_avg
2024-04-01124012401240.00
2024-04-0213151240, 13151277.50
2024-04-0312881240, 1315, 12881281.00
2024-04-0413921315, 1288, 13921331.67

The first frame uses the one available observation.

EXAMPLE QUERY
SELECT
  date_day,
  dau,
  ROUND(AVG(dau) OVER (
    ORDER BY date_day
    ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
  ), 2) AS moving_3_row_avg
FROM growth.daily_active_users
ORDER BY date_day;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario