Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 91/ 160
05. Window Functions & Analytical SQL

Moving Averages & Rolling Windows (7-Day, 30-Day Rolling Metrics)

Smooth noisy series with rolling 7-day and 30-day window averages.

IntermediateMoving Average · Rolling Window3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

For each day, average it together with the 6 days before it. As you move forward one day, the oldest day drops out.

Think of it like…

A cricket batter's average over their last 5 innings: each new innings pushes the oldest one out, so the number reflects current form, not their whole career.

Where you’ve seen it

A 7-day rolling average of daily signups, where days with no signups would otherwise be missing: join to a calendar first, then AVG(signups) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) over the complete series.

Words you’ll hear

Window frame
The rows included in each calculation: here, 6 preceding rows plus the current row.
Trailing window
Looks only backwards (today and the past N−1 days), as dashboards usually do.
ROWS vs RANGE offset
ROWS counts rows; RANGE BETWEEN INTERVAL '6 days' PRECEDING counts actual days.
Warm-up period
The first N−1 rows, which have fewer than N values in their window.

Visual diagram

Loading interactive diagram

Theory & example queries

Writing the frame

ROWS BETWEEN 6 PRECEDING AND CURRENT ROW means "this row and the 6 before it", which is 7 rows. Add PARTITION BY to compute separate rolling averages per product or region. A centered average (3 preceding and 3 following) smooths better for analysis but changes as new data arrives, so dashboards usually use trailing windows.

ROWS counts rows, not days. If Sunday has no row, the "7-day" window for Monday reaches back 8 days. Either fill the gaps by joining to a complete calendar (generate_series in PostgreSQL), or, in PostgreSQL 11+, use RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW, which looks at dates rather than row positions.

Fill gaps, then rollQuery example
1Input dataStart from the source rows or state that the statement sees.
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  days AS (3    SELECT4      d::date AS DAY5    FROM6      generate_series(7        '2026-10-01'::date,8        '2026-11-19',9        '1 day'10      ) d11  ),12  daily AS (13    SELECT14      days.day,15      COUNT(u.id) AS signups16    FROM17      days18      LEFT JOIN users u ON u.created_at::date = days.day19    GROUP BY20      days.day21  )22SELECT23  DAY,24  AVG(signups) OVER (25    ORDER BY26      DAY ROWS BETWEEN 6 PRECEDING27      AND CURRENT ROW28  ) AS signups_7d29FROM30  daily;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/30
3OutputInspect the representative rows, affected-row count, plan, or command status.
First four sample dates4 sample rows
First four sample dates
daysignupssignups_7d
2026-10-011212
2026-10-021815
2026-10-03010
2026-10-041010

Note: Sample signup counts are illustrative. The first windows are partial because only the rows from 2026-10-01 onward are available.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Fill missing days first, or the window silently covers more than 7 days.

Warm-up rows and rolling rates

The first 6 rows don't have 6 predecessors, so their "7-day" average covers 1 to 6 days. Count the rows in the same frame (COUNT(*) OVER (… same frame …)) and show NULL, or filter, until it reaches 7.

For ratios such as conversion rate, a rolling average of daily rates weights a quiet day the same as a busy one. The correct 7-day rate is SUM(conversions) over the window divided by SUM(visits) over the window.

Correct rolling conversion rate

SUM(conversions) OVER w::numeric / NULLIF(SUM(visits) OVER w, 0) … WINDOW w AS (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)

Key takeaway: Hide partial windows, and roll sums for rates, not averages of rates.
Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1GROUP BY

Aggregate to one row per day

Build a daily series first (per product or region if needed). Raw events can't be rolled by row.

SQL at this step
1GROUP BY2  created_at::date
What to watch at this step
Grain
one row per day
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A moving (rolling) average averages each row with a fixed number of rows before it, such as the last 7 days, using a window frame: AVG(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). It smooths out day-to-day noise so trends are visible.

Why it matters: Daily metrics jump around with weekends, holidays and campaigns; a 7-day average is what most dashboards actually chart. The traps are subtle: missing days make "7 rows" cover more than 7 days, and the first rows average over fewer days than you think. Analytics interviews test both.

When to reach for it

  • 7-day and 28-day trend lines on dashboards
  • Smoothing noisy daily metrics before comparing periods
  • Rolling conversion or error rates from rolling sums

When to avoid or be careful

  • Rolling over a series with missing days
  • Presenting the first N−1 values as full averages
  • Averaging daily rates instead of dividing rolling sums

Ways to compute a rolling average

ROWS frame on a gap-free daily series
Best for: Most dashboards

Strengths: Simple and works in every engine with window functions.

Watch out: Requires filling missing days first.

RANGE BETWEEN INTERVAL … PRECEDING
Best for: PostgreSQL 11+ when gaps are possible

Strengths: Measures actual days, not rows.

Watch out: Not supported in every database; days with no row still don't count as 0.

Self join on a date range
Best for: Engines without window frames

Strengths: Works everywhere.

Watch out: Much slower and more code.

Interview signals & numbers to know

When this topic comes up

  • “7-day rolling average”
  • “Smooth out the weekly pattern”
  • Trailing 30 days
  • Window frames
  • Time-series dashboards

Benchmarks & rules of thumb

6 PRECEDING -
+ current row = 7-day window
N − 1 -
warm-up rows with partial windows
PostgreSQL 11 -
RANGE with an interval offset

Common mistakes & follow-ups

Common interview mistakes

  • Using ROWS 6 PRECEDING on a series where weekends are missing, so the window covers 9 days.
  • Writing 7 PRECEDING and getting an 8-day average.
  • Reporting a rolling average of daily conversion rates instead of the rolling sum ratio.

Likely interviewer follow-ups

  • How do you make sure a 7-day window really covers 7 calendar days?
  • How would you compute a 7-day rolling average per product?
  • Why is the average of daily conversion rates different from the 7-day conversion rate?
Interview tip: Mention gap-filling before writing the window. It's the detail that separates a correct rolling metric from one that's quietly wrong on weekends.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Moving Averages & Rolling Windows (7-Day, 30-Day Rolling Metrics) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Calculating Running Totals & Cumulative Distributions
Next topic
Deduplicating Tables Using ROW_NUMBER() OVER (PARTITION BY ...)