Expert

Moving Averages: The Secret to Smooth Charts

SQL Mastery Team
March 28, 2026
5 min read

Welcome to **Day 66**. Today we're making dirty data look clean.

The Problem: The "Zig-Zag" Chart

If you track daily sales, your chart will likely jump up and down. Weekend sales are high, Mondays are low. It's hard to see the **trend**.

A **Moving Average** (or Rolling Average) smooths this out by averaging the last few days of data for every point on the chart.

The Syntax: ROWS BETWEEN

SELECT

sale_date,

revenue,

AVG(revenue) OVER(

ORDER BY sale_date

ROWS BETWEEN 6 PRECEDING AND CURRENT ROW

) as seven_day_moving_avg

FROM daily_sales;

How it works

This tells SQL: "For every row, look at the 6 rows before it and the current row (total of 7), and calculate their average."

Why it's useful

  • **Finance**: Tracking stock prices without day-to-day volatility.
  • **Logistics**: Predicting delivery times based on the last 50 shipments.
  • **SaaS**: Seeing user login trends without "Weekend dips" ruining the data.
  • Your Task for Today

    Calculate a 3-day moving average for your hypothetical revenue data.

    *Day 67: Window Frame Specification (ROWS vs RANGE).*

    Ready to put your knowledge into practice?

    Join SQL Mastery and learn through interactive exercises.