Course contentsShow
← Databases & SQL
Lesson 1825 of 1,95317. Analytics and Data PipelinesFree lesson

Calculating Moving Averages

Apply rolling windows to smooth out noise in volatile time-series datasets.

In this lesson, you will learn how to smooth out volatile fluctuations in time-series data using window functions to calculate moving averages.

Why Moving Averages?

When dealing with analytical datasets—such as daily stock prices, server traffic, or retail sales—raw data is often "noisy." Sudden spikes or drops can obscure underlying trends. A moving average helps surface these trends by calculating the mean of a variable over a sliding subset of time, effectively filtering out transient noise.

Implementing with Window Functions

To calculate a moving average in SQL, we rely on the OVER clause combined with frame specifications. A frame allows us to define the "window" of rows (e.g., the current row and the two preceding rows) that should be included in the calculation.

Consider a table daily_metrics with columns metric_date and sales_volume. To calculate a 7-day moving average, we partition the data (if necessary) and define our frame:

SELECT 
    metric_date,
    sales_volume,
    AVG(sales_volume) OVER (
        ORDER BY metric_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS moving_avg_7d
FROM daily_metrics;

Understanding the Frame

The clause ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is the core of this logic. It instructs the database engine to look at the current row and the six rows that came immediately before it in the ORDER BY sequence. By doing this for every row in the result set, we generate a continuous, smoothed line that represents the recent trend rather than the raw daily oscillation.

Performance Considerations

Since you are already familiar with Partitioning for Query Performance and Indexing Strategies, keep in mind that moving average calculations are compute-intensive on large datasets. If you are calculating these averages across millions of rows, ensure your metric_date column is indexed or part of a cluster key to avoid expensive sorts. If the data is queried frequently, consider pre-calculating these values using the Materialized Views pattern we discussed previously to shift the burden from query time to ingestion time.

Key Takeaway: Use the ROWS BETWEEN frame specification within a window function to transform volatile time-series data into a smoothed, actionable trend line.