SQL ROWS BETWEEN

Defines a frame by physical row position — count actual rows, ignore whether values tie.

What & Why

ROWS BETWEEN start AND end counts physical rows, full stop. Two rows with identical values are still two separate steps in a ROWS-based frame.

See How It Works

BUSINESS QUESTION

Growth calculates a seven-observation moving 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 seven_row_avg
FROM growth.daily_active_users
ORDER BY date_day;
RESULT — seven-row trailing average
date_daydauseven_row_avg
2024-04-0112401240.00
2024-04-0213151277.50
2024-04-0312881281.00
2024-04-0413921308.75

ROWS counts the available physical observations in each trailing frame.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario