Daily sales jump around. A slow Monday after a busy weekend, a big order on Thursday, a holiday with no sales at all. Looking at the raw numbers, it’s hard to tell whether business is actually going up or down.
A moving average (or rolling average) smooths that noise by averaging each day with the few days before it. A rolling sum does the same with totals: “sales in the last 7 days” on every row. Both are one line of SQL with a window function, and both have one trap that catches almost everyone: missing days.
This guide shows how to calculate moving averages and rolling sums in SQL Server, MySQL and PostgreSQL, how window frames work, and how to get the right answer when some dates have no rows.

Table of Contents
The sample data
Ten days of sales. Note that 6 November is missing: the shop was closed.
CREATE TABLE DailySales (
SaleDate DATE PRIMARY KEY,
Amount DECIMAL(10,2)
);
INSERT INTO DailySales VALUES
('2026-11-01', 120), ('2026-11-02', 150), ('2026-11-03', 90),
('2026-11-04', 200), ('2026-11-05', 170), ('2026-11-07', 60),
('2026-11-08', 210), ('2026-11-09', 180), ('2026-11-10', 130),
('2026-11-11', 240);
A 3-day moving average
SELECT SaleDate,
Amount,
CAST(AVG(Amount) OVER (ORDER BY SaleDate
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
AS DECIMAL(10,2)) AS MovingAvg3
FROM DailySales
ORDER BY SaleDate;
| SaleDate | Amount | MovingAvg3 |
|---|---|---|
| 2026-11-01 | 120.00 | 120.00 |
| 2026-11-02 | 150.00 | 135.00 |
| 2026-11-03 | 90.00 | 120.00 |
| 2026-11-04 | 200.00 | 146.67 |
| 2026-11-05 | 170.00 | 153.33 |
| 2026-11-07 | 60.00 | 143.33 |
| 2026-11-08 | 210.00 | 146.67 |
| 2026-11-09 | 180.00 | 150.00 |
| 2026-11-10 | 130.00 | 173.33 |
| 2026-11-11 | 240.00 | 183.33 |
The raw amounts swing between 60 and 240; the moving average moves gently from 120 to 183. That steady climb is the trend.
The important part is the window frame: ROWS BETWEEN 2 PRECEDING AND CURRENT ROW. For each row, SQL looks at that row and the two rows before it (in SaleDate order) and averages them. On 4 November the three rows are 2, 3 and 4 November: (150 + 90 + 200) / 3 = 146.67.
The CAST to DECIMAL(10,2) just rounds the display. Without it, SQL Server shows many decimal places.
If you’re new to OVER (...), read SQL Window Functions Explained Simply first. A running total is the same idea with a frame that starts at the first row instead of 2 rows back.
The first rows have a shorter window
Look at 1 and 2 November. There aren’t two earlier rows yet, so the “3-day” average is really a 1-day and a 2-day average. Charts drawn from this data start with a misleading flat line.
The fix is to count the rows in the frame and show NULL until the window is full:
SELECT SaleDate,
Amount,
CASE WHEN COUNT(*) OVER (ORDER BY SaleDate
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) = 3
THEN CAST(AVG(Amount) OVER (ORDER BY SaleDate
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
AS DECIMAL(10,2))
END AS MovingAvg3
FROM DailySales
ORDER BY SaleDate;
Now 1 and 2 November show NULL, and the average starts on 3 November (120.00).
In MySQL 8 and PostgreSQL you can name the window once to avoid repeating it:
SELECT SaleDate, Amount,
CASE WHEN COUNT(*) OVER w = 3 THEN ROUND(AVG(Amount) OVER w, 2) END AS MovingAvg3
FROM DailySales
WINDOW w AS (ORDER BY SaleDate ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
ORDER BY SaleDate;
The WINDOW clause arrived in SQL Server 2022, so on older versions write the frame out each time.
A 7-day rolling sum, and the missing-day trap
“Sales in the last 7 days” looks like it should be:
SELECT SaleDate, Amount,
SUM(Amount) OVER (ORDER BY SaleDate
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS Rolling7
FROM DailySales;
But ROWS counts rows, not days. On 8 November the frame covers the 7 rows from 1 to 8 November, which is 8 calendar days, because 6 November has no row. The result is 1,000 when the true 7-day total (2 to 8 November) is 880.
| SaleDate | ROWS 6 PRECEDING | True last 7 days |
|---|---|---|
| 2026-11-07 | 790.00 | 790.00 |
| 2026-11-08 | 1000.00 | 880.00 |
| 2026-11-09 | 1060.00 | 910.00 |
| 2026-11-10 | 1040.00 | 950.00 |
| 2026-11-11 | 1190.00 | 990.00 |
Every row after the gap is wrong, and nothing warns you. Real sales data almost always has gaps: weekends, holidays, products that didn’t sell. There are three ways to fix it.
Fix 1: fill the missing days first (works everywhere)
Join to a list of every date, use 0 for days with no sales, and then use ROWS. Now one row really is one day.
With a calendar table (the cleanest option in SQL Server):
SELECT c.CalendarDate AS SaleDate,
COALESCE(s.Amount, 0) AS Amount,
SUM(COALESCE(s.Amount, 0)) OVER (ORDER BY c.CalendarDate
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS Rolling7Days
FROM dbo.Calendar AS c
LEFT JOIN dbo.DailySales AS s ON s.SaleDate = c.CalendarDate
WHERE c.CalendarDate BETWEEN '2026-11-01' AND '2026-11-11'
ORDER BY c.CalendarDate;
Without a calendar table, generate the dates with a recursive CTE (MySQL 8 syntax shown; in SQL Server drop the word RECURSIVE, write the anchor as CAST('2026-11-01' AS DATE) and use DATEADD(day, 1, d); in PostgreSQL, generate_series is simpler):
WITH RECURSIVE Days AS (
SELECT DATE '2026-11-01' AS d
UNION ALL
SELECT d + INTERVAL 1 DAY FROM Days WHERE d < '2026-11-11'
),
Filled AS (
SELECT Days.d AS SaleDate, COALESCE(s.Amount, 0) AS Amount
FROM Days
LEFT JOIN DailySales AS s ON s.SaleDate = Days.d
)
SELECT SaleDate, Amount,
SUM(Amount) OVER (ORDER BY SaleDate
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS Rolling7Days
FROM Filled
ORDER BY SaleDate;
6 November now appears with 0, and the totals are right (880, 910, 950, 990).
Decide whether a missing day means zero. For sales it does. For a temperature reading or a stock price it doesn’t, and the average should skip the day rather than count it as 0.
Fix 2: RANGE with an interval (MySQL 8, PostgreSQL, Oracle)
These databases let the frame be defined by value instead of by row count:
-- MySQL 8.0 / PostgreSQL 11+
SELECT SaleDate, Amount,
SUM(Amount) OVER (ORDER BY SaleDate
RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW) AS Rolling7Days
FROM DailySales;
(PostgreSQL writes it INTERVAL '6 days'.) This includes every row whose date is within 6 days before the current one, gaps or not. SQL Server doesn’t support RANGE with an interval, and MariaDB doesn’t either.
Fix 3: a self-join by date (works everywhere, slower)
SELECT d.SaleDate, d.Amount, SUM(p.Amount) AS Rolling7Days
FROM DailySales AS d
JOIN DailySales AS p
ON p.SaleDate BETWEEN DATEADD(day, -6, d.SaleDate) AND d.SaleDate -- SQL Server
GROUP BY d.SaleDate, d.Amount
ORDER BY d.SaleDate;
In MySQL use DATE_SUB(d.SaleDate, INTERVAL 6 DAY). It’s easy to read and correct, but it reads the table once per row, so it slows down on large tables. Fine for a few thousand rows; use fix 1 beyond that.
Moving averages per product
Add PARTITION BY to restart the window for each product (or customer, or branch):
SELECT ProductID, SaleDate, Qty,
CAST(AVG(Qty * 1.0) OVER (PARTITION BY ProductID
ORDER BY SaleDate
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
AS DECIMAL(10,2)) AS Avg3
FROM ProductSales
ORDER BY ProductID, SaleDate;
| ProductID | SaleDate | Qty | Avg3 |
|---|---|---|---|
| 1 | 2026-11-01 | 10 | 10.00 |
| 1 | 2026-11-02 | 14 | 12.00 |
| 1 | 2026-11-03 | 9 | 11.00 |
| 1 | 2026-11-04 | 13 | 12.00 |
| 2 | 2026-11-01 | 3 | 3.00 |
| 2 | 2026-11-02 | 5 | 4.00 |
| 2 | 2026-11-03 | 4 | 4.00 |
| 2 | 2026-11-04 | 8 | 5.67 |
Product 2’s window doesn’t borrow product 1’s numbers. A 3-day average of quantity is a simple way to set reorder levels for stock.
The * 1.0 matters in SQL Server: AVG of an integer column returns an integer there, so without it product 2’s last average would show 5.00 instead of 5.67. MySQL returns a decimal anyway.
Other useful frames
The frame can look forward as well as back, and any aggregate works inside it.
Centred moving average (yesterday, today, tomorrow), often used to smooth a chart:
AVG(Amount) OVER (ORDER BY SaleDate ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
Highest value in the last 3 rows, and how far today is above or below the average:
SELECT SaleDate, Amount,
MAX(Amount) OVER (ORDER BY SaleDate ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS Max3,
Amount - AVG(Amount) OVER (ORDER BY SaleDate ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS VsAvg3
FROM DailySales;
A large positive VsAvg3 flags an unusual day worth checking: a big customer order, or a data entry mistake (see Basic Statistics in SQL for a more formal way to spot outliers).
The default frame trap
If you write ORDER BY inside OVER but no frame, the default is:
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
That’s a running total from the first row, not a moving window. So this:
SUM(Amount) OVER (ORDER BY SaleDate)
returns 120, 270, 360, 560… growing forever. Always write the frame explicitly when you want a moving window.
Two more reasons to write ROWS explicitly:
- With
RANGE, rows that share the sameORDER BYvalue (two sales on the same date) are treated as one group and all get the same result.ROWStreats them one by one. - In SQL Server,
ROWSframes are processed in memory, while the defaultRANGEframe uses an on-disk worktable. On large tablesROWSis noticeably faster.
Common mistakes
- Using
ROWSon data with missing dates and getting a window wider than you think. - Forgetting the frame, so the “moving” average is really a running average since the first row.
- Counting missing days as 0 for measurements where they should be skipped.
- Showing partial windows at the start of the period as if they were full.
- Integer averages in SQL Server losing the decimals.
- No tie-breaker: if two rows can share a date, add a unique column to the
ORDER BYso results are repeatable.
Practice exercises
Exercise 1. Write a 4-row moving average of Amount that shows NULL until four rows are available.
Exercise 2. Using the DailySales data, what does SUM(Amount) OVER (ORDER BY SaleDate ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) return for 7 November? And what is the true total for the 3 calendar days 5 to 7 November?
Exercise 3. Write a query that returns each date with its amount and the average of the previous 3 rows, not including today (useful as a “forecast” to compare against).
Answers
Answer 1.
SELECT SaleDate, Amount,
CASE WHEN COUNT(*) OVER (ORDER BY SaleDate ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) = 4
THEN CAST(AVG(Amount) OVER (ORDER BY SaleDate ROWS BETWEEN 3 PRECEDING AND CURRENT ROW)
AS DECIMAL(10,2))
END AS MovingAvg4
FROM DailySales
ORDER BY SaleDate;
The first value appears on 4 November: (120 + 150 + 90 + 200) / 4 = 140.00.
Answer 2. The ROWS version returns 430 (4, 5 and 7 November: 200 + 170 + 60), because it takes the last 3 rows (the current row and the 2 before it). The true 3-day total for 5 to 7 November is 230 (170 + 0 + 60).
Answer 3.
SELECT SaleDate, Amount,
CAST(AVG(Amount) OVER (ORDER BY SaleDate
ROWS BETWEEN 3 PRECEDING AND 1 PRECEDING)
AS DECIMAL(10,2)) AS Prev3Avg
FROM DailySales
ORDER BY SaleDate;
The frame ends at 1 PRECEDING, so today isn’t included. The first row returns NULL (no previous rows).
Summary
- A moving average is
AVG(...) OVER (ORDER BY date ROWS BETWEEN n PRECEDING AND CURRENT ROW); a rolling sum usesSUMthe same way. ROWScounts rows, not days. With missing dates, fill them from a calendar table, useRANGE ... INTERVAL(MySQL 8, PostgreSQL), or self-join on a date range.- Use
COUNT(*) OVERthe same frame to hide incomplete windows at the start. PARTITION BYgives a separate moving average per product, customer or branch.- Always write the frame explicitly; the default is a running total.
Free SQL book for beginners
New to window functions? My free book, Simplify SQL for Absolute Beginners, introduces them in Chapter 22 of the full book, on ShopDB, a practice database with 18 months of orders. Chapters 1–3 are free now as a PDF and EPUB.
Related articles
- SQL Window Functions Explained Simply: OVER, PARTITION BY and ORDER BY from the start.
- Running Totals in SQL: the frame that starts at the first row.
- Calendar Table in SQL: one row per day, so ROWS really means days.
- Month-over-Month and Year-over-Year Comparisons in SQL: compare periods with LAG.