SQL & Relational Database Mastery · Chapter 8 · ~15 min · Advanced
Running Totals, Moving Averages & Percentiles
Frame sliding windows with ROWS BETWEEN, compute rolling metrics, and calculate percentiles with NTILE and PERCENT_RANK.
- Frame sliding windows with ROWS BETWEEN UNBOUNDED PRECEDING and CURRENT ROW
- Smooth noisy trends using rolling multi-day moving averages (AVG OVER)
- Segment distributions into balanced cohorts using NTILE and CUME_DIST
- Compute percentile ranks and cumulative distributions across high-volume partitions
Running Totals, Moving Averages & Percentiles: learn it visually
Frame sliding windows with ROWS BETWEEN, compute rolling metrics, and calculate percentiles with NTILE and PERCENT_RANK.
1The Viewfinder: How Window Frames Actually Work
In Chapter 7, you discovered that OVER (PARTITION BY ... ORDER BY ...) lets rows calculate rankings without collapsing into a single summary row. But what happens when you write an aggregate like SUM(revenue) OVER (ORDER BY date)?
Behind the scenes, the SQL query engine places a physical window frame (like a sliding viewfinder) over a subset of rows relative to the row currently being evaluated.
Wrong idea: ORDER BY inside OVER() sums all rows in the partition
Assuming 'SUM(amount) OVER (ORDER BY date)' calculates a grand total across all rows without understanding the implicit frame.
Real system: Explicit 'ROWS BETWEEN' guarantees deterministic row-by-row framing
Specifying 'ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW' counts physical records, preventing duplicate date values from bunching up into identical sums.
By default, whenever you include an ORDER BY clause inside an OVER() block, SQL applies an implicit frame:
-- Default implicit window frame when ORDER BY is present:
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWWhat is the default window frame applied in SQL when an ORDER BY is specified inside OVER() without an explicit ROWS clause?
2Running Totals & Rolling Moving Averages
Let us examine the exact anatomy of the ROWS BETWEEN syntax. You define both the frame start and frame end:
-- Cumulative Running Total per Customer:
SELECT
order_date,
customer_id,
amount,
SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS customer_cumulative_spend
FROM orders;From the Start
Starts at the very first row of the partition and accumulates up to the current row.
Bounded Rolling Lookback
Looks back exactly N rows. For a 7-day moving average, use ROWS BETWEEN 6 PRECEDING AND CURRENT ROW.
Centered Windows
Smooths sensor or financial time-series symmetrically: ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING.
-- 7-Day Rolling Moving Average to smooth weekly seasonality:
SELECT
sale_date,
daily_revenue,
ROUND(
AVG(daily_revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
),
2
) AS moving_avg_7day
FROM daily_sales;To calculate a 3-day moving average that includes today's revenue and the previous 2 days, which frame clause is required?
3Interactive Visualizer: Watch the Window Slide
Observe how the viewfinder bracket slides across daily records. Select different calculation modes and click any day button to inspect the rows included in each window frame:
Interactive Window Frame & Sliding Slice Visualizer
Sliding Window Frame Bracket & Metric Curve
4Percentiles, Quartiles & Cohorts: NTILE, PERCENT_RANK & CUME_DIST
Enterprise analytics frequently requires ranking customers or transactions into percentiles (e.g., top 1% power users, quartile spenders, or SLA compliance percentiles). SQL provides three distinct statistical ranking functions:
1. NTILE(n) — Equal-Sized Bucket Segmentation
Divides an ordered partition into n numbered buckets (from 1 to n). If the row count is not evenly divisible, earlier buckets receive the extra rows.
SELECT
customer_id,
annual_spend,
NTILE(4) OVER (ORDER BY annual_spend DESC) AS spend_quartile
FROM customers;2. PERCENT_RANK() — Relative Positional Rank (0.0 to 1.0)
Computes the relative rank of a row using the formula: (rank - 1) / (total_rows - 1). The top row always evaluates to 0.0 and the bottom row evaluates to 1.0.
SELECT
employee_id,
salary,
ROUND(PERCENT_RANK() OVER (ORDER BY salary ASC)::numeric, 4) AS salary_percentile
FROM employees;3. CUME_DIST() — Cumulative Distribution Frequency
Calculates the cumulative distribution of a value: number_of_rows_with_value_less_or_equal / total_rows. Useful for finding what percentage of queries complete within 200ms.
SELECT
query_id,
latency_ms,
CUME_DIST() OVER (ORDER BY latency_ms ASC) AS cumulative_latency_pct
FROM query_logs;If a table has 10 rows and you run NTILE(4) OVER (ORDER BY revenue DESC), how are the rows distributed across the 4 buckets?
5Bug Hunt: Fix Rolling Revenue & Percentiles
A financial analytics dashboard has three critical bugs in its rolling revenue report. The cumulative spend is jumping erratically, the 3-day moving average is excluding today's sales, and customer quartiles are using the wrong bucket count.
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
• Make sure the running total orders by order_date and specifies ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
• Fix the 3-day moving average frame to ROWS BETWEEN 2 PRECEDING AND CURRENT ROW.
• Update NTILE(10) to NTILE(4) for quartiles.
6Production Tuning: Memory Spills and Indexes
Window functions operate after WHERE, GROUP BY, and HAVING clauses. The database must sort the rows for each unique PARTITION BY and ORDER BY combination.
In PostgreSQL, if the data size exceeds work_mem, the query engine spills intermediate sort runs to local disk (visible in EXPLAIN ANALYZE as Sort Method: external merge Disk).
Which composite index enables a query planner to compute 'SUM(amount) OVER (PARTITION BY store_id ORDER BY tx_time)' without sorting in memory?
7Recap
- An
ORDER BYinsideOVER()defaults toRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which aggregates identical values simultaneously. - Always specify
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWfor deterministic, row-by-row cumulative running sums. - Calculate moving averages by bounding lookback frames, such as
ROWS BETWEEN 6 PRECEDING AND CURRENT ROWfor a 7-day smoothing window. - Use
NTILE(k)for equal-sized bucket segmentation (quartiles, deciles), andPERCENT_RANK()for true mathematical relative percentiles from 0.0 to 1.0.
Ready for Chapter 9? Dive into Indexes & The B-Tree Engine: