SQL RANGE BETWEEN

Defines a frame by value, not row position — tied rows are treated as arriving together.

What & Why

A RANGE BETWEEN frame includes peers and rows whose ORDER BY value falls within the specified value interval. It creates a true calendar-time window even when some dates have no row or several rows share an ordered value.

See How It Works

BUSINESS QUESTION

Growth calculates DAU averages over the current date and prior six calendar days.

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::timestamp
    RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW
  ), 2) AS seven_day_avg
FROM growth.daily_active_users
ORDER BY date_day;
RESULT — seven-day trailing average
date_daydauseven_day_avg
2024-04-0112401240.00
2024-04-0213151277.50
2024-04-0312881281.00
2024-04-0413921308.75

All four representative dates fall within six days of the current row.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario