Interview Question: "Explain the difference between running total and moving average. How do you calculate year-over-year growth using window functions? What are the performance implications?" â Asked at Tableau, Looker, Databricks for Analytics roles
âšī¸
Difficulty: Advanced | Companies: Tableau, Looker, Databricks, Snowflake, Google BigQuery | Time: 45-60 minutes
Running Totals
A running total accumulates values in ORDER BY sequence: each row's result is the sum of everything from the start of the partition through the current row. It answers "how much so far?" questions â revenue to date, cumulative signups, inventory position after each transaction. The frame ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is the default when ORDER BY is present and no frame is written, which is why SUM(revenue) OVER (ORDER BY sale_date) already produces the accumulation you expect.
-- Create sales data
CREATE TABLE daily_sales (
sale_date DATE PRIMARY KEY,
revenue DECIMAL(12,2),
units_sold INT
);
INSERT INTO daily_sales VALUES
('2024-01-01', 15000.00, 150),
('2024-01-02', 18000.00, 180),
('2024-01-03', 16500.00, 165),
('2024-01-04', 21000.00, 210),
('2024-01-05', 19500.00, 195),
('2024-01-08', 22000.00, 220),
('2024-01-09', 24000.00, 240),
('2024-01-10', 20500.00, 205),
('2024-01-11', 25500.00, 255),
('2024-01-12', 27000.00, 270);
-- Running total
SELECT
sale_date,
revenue,
SUM(revenue) OVER (ORDER BY sale_date) AS running_total,
SUM(units_sold) OVER (ORDER BY sale_date) AS running_units,
-- Running average
AVG(revenue) OVER (ORDER BY sale_date) AS running_avg
FROM daily_sales
ORDER BY sale_date;
Output:
| sale_date | revenue | running_total | running_units | running_avg |
|---|---|---|---|---|
| 2024-01-01 | 15000.00 | 15000.00 | 150 | 15000.00 |
| 2024-01-02 | 18000.00 | 33000.00 | 330 | 16500.00 |
| 2024-01-03 | 16500.00 | 49500.00 | 495 | 16500.00 |
| 2024-01-04 | 21000.00 | 70500.00 | 705 | 17625.00 |
| 2024-01-05 | 19500.00 | 90000.00 | 900 | 18000.00 |
| 2024-01-08 | 22000.00 | 112000.00 | 1120 | 18666.67 |
| 2024-01-09 | 24000.00 | 136000.00 | 1360 | 19428.57 |
| 2024-01-10 | 20500.00 | 156500.00 | 1565 | 19562.50 |
| 2024-01-11 | 25500.00 | 182000.00 | 1820 | 20222.22 |
| 2024-01-12 | 27000.00 | 209000.00 | 2090 | 20900.00 |
Moving Averages
A simple moving average (SMA) averages a fixed window of the k most recent rows, so each new observation enters and the oldest one drops out. The frame ROWS BETWEEN 2 PRECEDING AND CURRENT ROW gives a 3-row SMA: the first two output rows are averages of partial windows, a warm-up effect you must either suppress with a row-count guard or accept in the chart. A weighted moving average multiplies each value by a weight column before summing, then divides by the summed weights over the same frame â useful when recent days should count more without the decay of an exponential model.
An exponential moving average (EMA) applies geometric decay instead of a hard cutoff: today's value is alpha * x + (1 - alpha) * previous, so influence halves roughly every log(0.5) / log(1 - alpha) periods. With alpha = 0.3 that is about 2 observations. SQL has no built-in recursive window aggregate, so the usual pattern is a self-join chain or a two-pass approach; the CASE query below shows the one-step lookback that works when the previous EMA equals the previous raw value, which is only correct for the first lag â true multi-step EMAs need a recursive CTE or application-side iteration.
-- Simple Moving Average (SMA)
SELECT
sale_date,
revenue,
-- 3-day SMA
AVG(revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS sma_3day,
-- 5-day SMA
AVG(revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN 4 PRECEDING AND CURRENT ROW
) AS sma_5day,
-- Weighted Moving Average
SUM(revenue * weight) OVER (
ORDER BY sale_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) / SUM(weight) OVER (
ORDER BY sale_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS wma_3day
FROM daily_sales
ORDER BY sale_date;
-- Exponential Moving Average (EMA)
WITH ema_calc AS (
SELECT
sale_date,
revenue,
0.3 AS alpha, -- Smoothing factor
LAG(revenue) OVER (ORDER BY sale_date) AS prev_revenue
FROM daily_sales
)
SELECT
sale_date,
revenue,
CASE
WHEN prev_revenue IS NULL THEN revenue
ELSE alpha * revenue + (1 - alpha) * prev_revenue
END AS ema
FROM ema_calc
ORDER BY sale_date;
Cumulative Distribution
-- Cumulative distribution
SELECT
sale_date,
revenue,
CUME_DIST() OVER (ORDER BY revenue) AS cumulative_dist,
PERCENT_RANK() OVER (ORDER BY revenue) AS percentile_rank,
NTILE(4) OVER (ORDER BY revenue) AS quartile,
NTILE(10) OVER (ORDER BY revenue) AS decile
FROM daily_sales
ORDER BY sale_date;
Output:
| sale_date | revenue | cumulative_dist | percentile_rank | quartile | decile |
|---|---|---|---|---|---|
| 2024-01-01 | 15000.00 | 0.10 | 0.00 | 1 | 1 |
| 2024-01-02 | 18000.00 | 0.20 | 0.11 | 1 | 2 |
| 2024-01-03 | 16500.00 | 0.30 | 0.22 | 2 | 3 |
| 2024-01-04 | 21000.00 | 0.40 | 0.33 | 2 | 4 |
| 2024-01-05 | 19500.00 | 0.50 | 0.44 | 3 | 5 |
| 2024-01-08 | 22000.00 | 0.60 | 0.55 | 3 | 6 |
| 2024-01-09 | 24000.00 | 0.70 | 0.66 | 4 | 7 |
| 2024-01-10 | 20500.00 | 0.80 | 0.77 | 4 | 8 |
| 2024-01-11 | 25500.00 | 0.90 | 0.88 | 4 | 9 |
| 2024-01-12 | 27000.00 | 1.00 | 1.00 | 4 | 10 |
Period-Over-Period Growth with LAG
LAG pulls a value from a preceding row without a self-join. The offset is in rows, not calendar units, so LAG(revenue, 7) means "seven rows back" â it equals "one week ago" only if the table has exactly one row per day with no gaps. The sample table skips weekends (2024-01-06 and 2024-01-07 are missing), so a 7-row offset actually reaches back more than a week. When the calendar matters, aggregate to a dense daily spine first (generate_series or a recursive date CTE), left join the facts onto it, then apply LAG. Division always goes through NULLIF: the first row of each partition has no predecessor, and dividing by NULL must yield NULL rather than crash or silently report infinity.
-- Year-over-year growth
SELECT
sale_date,
revenue,
LAG(revenue, 1) OVER (ORDER BY sale_date) AS prev_day,
LAG(revenue, 7) OVER (ORDER BY sale_date) AS prev_week,
LAG(revenue, 365) OVER (ORDER BY sale_date) AS prev_year,
-- Day-over-day growth
ROUND(
(revenue - LAG(revenue, 1) OVER (ORDER BY sale_date)) * 100.0 /
NULLIF(LAG(revenue, 1) OVER (ORDER BY sale_date), 0), 2
) AS dod_growth,
-- Week-over-week growth
ROUND(
(revenue - LAG(revenue, 7) OVER (ORDER BY sale_date)) * 100.0 /
NULLIF(LAG(revenue, 7) OVER (ORDER BY sale_date), 0), 2
) AS wow_growth
FROM daily_sales
ORDER BY sale_date;
Advanced Window Aggregates
-- Standard deviation and variance
SELECT
sale_date,
revenue,
AVG(revenue) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_avg,
STDDEV(revenue) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_stddev,
VARIANCE(revenue) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_variance,
-- Coefficient of variation
ROUND(
STDDEV(revenue) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) * 100.0 /
NULLIF(AVG(revenue) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), 0),
2
) AS cv_percent
FROM daily_sales
ORDER BY sale_date;
-- First and last values in window
SELECT
sale_date,
revenue,
FIRST_VALUE(revenue) OVER (ORDER BY sale_date) AS first_value,
LAST_VALUE(revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_value,
NTH_VALUE(revenue, 3) OVER (ORDER BY sale_date) AS third_value
FROM daily_sales
ORDER BY sale_date;
Performance Considerations
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Running Total | ||
| Moving Average | ||
| Cumulative Dist | ||
| YoY Growth |
-- Optimize window functions
EXPLAIN (ANALYZE, BUFFERS)
SELECT
sale_date,
SUM(revenue) OVER (ORDER BY sale_date) AS running_total
FROM daily_sales;
-- Check for sort operations
EXPLAIN (ANALYZE, BUFFERS)
SELECT
sale_date,
AVG(revenue) OVER (ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS sma
FROM daily_sales;
âšī¸
Pro Tip: Window functions are computed after WHERE but before ORDER BY. Use CTEs to break complex calculations into readable steps.
Mathematical Properties
For running total :
For exponential moving average:
The smoothing factor controls responsiveness:
Choosing Between CUME_DIST, PERCENT_RANK, and NTILE
All three rank rows inside a partition, but they answer different questions. CUME_DIST returns the fraction of rows at or below the current row, so the highest value always scores 1.0 and ties share the higher score â it answers "what share of observations is at or below this point?", which is the right tool for SLA reports such as "95 percent of orders shipped below X hours". PERCENT_RANK maps the lowest row to 0.0 and averages tie positions, making it the cleaner choice for relative standing on a 0-to-1 scale. NTILE ignores fractional positions entirely: it forces rows into n roughly equal buckets, which is what you want for quartile flags and decile segmentation even though bucket sizes can differ by one row when n does not divide the partition.
PERCENTILE_CONT with WITHIN GROUP (ORDER BY ...) interpolates between neighbors to produce a value that may not exist in the data (the 20250.00 median above sits between the fifth and sixth revenues), while the discrete cousins PERCENTILE_DISC always return an actual observed value. Pick continuous for statistical thresholds, discrete when the number must be something you can point to in the source table.
-- CDF and percentiles
SELECT
sale_date,
revenue,
CUME_DIST() OVER (ORDER BY revenue) AS cume_dist,
PERCENT_RANK() OVER (ORDER BY revenue) AS percent_rank,
NTILE(4) OVER (ORDER BY revenue) AS quartile,
NTILE(10) OVER (ORDER BY revenue) AS decile,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY revenue) OVER () AS median
FROM daily_sales
ORDER BY sale_date;
Output:
| sale_date | revenue | cume_dist | percent_rank | quartile | decile | median |
|---|---|---|---|---|---|---|
| 2024-01-01 | 15000.00 | 0.10 | 0.00 | 1 | 1 | 20250.00 |
| 2024-01-02 | 18000.00 | 0.20 | 0.11 | 1 | 2 | 20250.00 |
| 2024-01-03 | 16500.00 | 0.30 | 0.22 | 2 | 3 | 20250.00 |
| 2024-01-04 | 21000.00 | 0.40 | 0.33 | 2 | 4 | 20250.00 |
| 2024-01-05 | 19500.00 | 0.50 | 0.44 | 3 | 5 | 20250.00 |
| 2024-01-08 | 22000.00 | 0.60 | 0.55 | 3 | 6 | 20250.00 |
| 2024-01-09 | 24000.00 | 0.70 | 0.66 | 4 | 7 | 20250.00 |
| 2024-01-10 | 20500.00 | 0.80 | 0.77 | 4 | 8 | 20250.00 |
| 2024-01-11 | 25500.00 | 0.90 | 0.88 | 4 | 9 | 20250.00 |
| 2024-01-12 | 27000.00 | 1.00 | 1.00 | 4 | 10 | 20250.00 |
Moving Percentiles
-- 7-day moving percentile
SELECT
sale_date,
revenue,
PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_q1,
PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_median,
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_q3,
PERCENTILE_CONT(0.90) WITHIN GROUP (ORDER BY revenue) OVER (
ORDER BY sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_p90
FROM daily_sales
ORDER BY sale_date;
Z-Score and Outlier Detection
-- Calculate z-scores using window functions
WITH stats AS (
SELECT
sale_date,
revenue,
AVG(revenue) OVER () AS mean_revenue,
STDDEV(revenue) OVER () AS stddev_revenue
FROM daily_sales
)
SELECT
sale_date,
revenue,
ROUND(mean_revenue, 2) AS mean,
ROUND(stddev_revenue, 2) AS stddev,
ROUND((revenue - mean_revenue) / NULLIF(stddev_revenue, 0), 4) AS z_score,
CASE
WHEN ABS((revenue - mean_revenue) / NULLIF(stddev_revenue, 0)) > 2 THEN 'OUTLIER'
WHEN ABS((revenue - mean_revenue) / NULLIF(stddev_revenue, 0)) > 1.5 THEN 'UNUSUAL'
ELSE 'NORMAL'
END AS classification
FROM stats
ORDER BY sale_date;
Output:
| sale_date | revenue | mean | stddev | z_score | classification |
|---|---|---|---|---|---|
| 2024-01-01 | 15000.00 | 20900.00 | 4178.51 | -1.4117 | NORMAL |
| 2024-01-02 | 18000.00 | 20900.00 | 4178.51 | -0.6940 | NORMAL |
| 2024-01-03 | 16500.00 | 20900.00 | 4178.51 | -1.0529 | NORMAL |
| 2024-01-04 | 21000.00 | 20900.00 | 4178.51 | 0.0239 | NORMAL |
| 2024-01-05 | 19500.00 | 20900.00 | 4178.51 | -0.3350 | NORMAL |
| 2024-01-08 | 22000.00 | 20900.00 | 4178.51 | 0.2633 | NORMAL |
| 2024-01-09 | 24000.00 | 20900.00 | 4178.51 | 0.7419 | NORMAL |
| 2024-01-10 | 20500.00 | 20900.00 | 4178.51 | -0.0957 | NORMAL |
| 2024-01-11 | 25500.00 | 20900.00 | 4178.51 | 1.1009 | NORMAL |
| 2024-01-12 | 27000.00 | 20900.00 | 4178.51 | 1.4599 | NORMAL |
Performance Analysis
-- Compare window function performance
EXPLAIN (ANALYZE, BUFFERS)
SELECT
sale_date,
SUM(revenue) OVER (ORDER BY sale_date) AS running_total,
AVG(revenue) OVER (ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS sma_3,
LAG(revenue, 1) OVER (ORDER BY sale_date) AS prev_value
FROM daily_sales;
-- Check sort operations
EXPLAIN (ANALYZE, BUFFERS)
SELECT
sale_date,
revenue,
RANK() OVER (ORDER BY revenue DESC) AS rank
FROM daily_sales;
Window Function Optimization Tips
- Partition wisely: Use PARTITION BY to reduce window size
- Frame bounds: Use precise ROWS bounds instead of RANGE
- Index support: Ensure ORDER BY columns are indexed
- Avoid repeated sorts: Combine window functions with same ORDER BY
- Materialize CTEs: Use MATERIALIZED for complex window calculations
âšī¸
Performance Tip: Window functions are computed after WHERE but before ORDER BY. Use CTEs to break complex calculations into readable steps.
Edge Cases: NULLs, Gaps, and Empty Frames
Three failure modes account for most window-aggregate bugs. NULL measures: SUM ignores NULLs but COUNT(column) skips them too, so a day with revenue NULL contributes nothing to a running SUM yet still consumes a row in a ROWS frame â the running total jumps by zero while the row count advances, which silently distorts any downstream average computed as total divided by row number. Calendar gaps: every frame in this lesson orders by sale_date with ROWS bounds, so "3-day average" really means "average of the last 3 observed rows". On the sample data the gap between 2024-01-05 and 2024-01-08 makes the 3-row SMA on 2024-01-08 average Friday, Monday and Tuesday together. If the business definition is calendar days, densify the series first or switch the frame to RANGE with an INTERVAL bound. Empty frames: FIRST_VALUE, LAST_VALUE and NTH_VALUE return NULL when the frame contains no rows yet, so always check the warm-up rows before feeding them into alerts.
Common Mistakes
Treating ROWS BETWEEN n PRECEDING as a calendar window when the table has gaps
Fix: Densify to a continuous date spine, or use RANGE BETWEEN INTERVAL bounds so weekends and holidays drop out by value
Dividing a running SUM by COUNT(*) to get a running average
Fix: Use AVG(revenue) OVER (ORDER BY sale_date) directly â it counts only non-NULL values in the frame
Recomputing the same ORDER BY window with a different PARTITION BY and wondering why the plan sorts twice
Fix: Share one window definition with the WINDOW clause so the planner reuses a single sort
Key Takeaways
- Running totals use UNBOUNDED PRECEDING frames; moving averages use fixed ROWS bounds â the first two rows of an SMA are partial-window warm-ups
- LAG offsets count rows, not calendar days â densify the series before claiming a 7-row lag equals one week
- CUME_DIST, PERCENT_RANK and NTILE answer different ranking questions; PERCENTILE_CONT interpolates while PERCENTILE_DISC returns an observed value
- Z-score outlier detection is a two-step window: partition-free AVG/STDDEV in a CTE, then classify in the outer query with NULLIF-guarded division
â ī¸
Edge Cases: Window functions return NULL for rows where the frame is empty. Handle with COALESCE or CASE statements.