When you need it
"Cumulative revenue by day", "7-day moving average", "balance after each transaction", "days since the previous order", "change from the last reading". Words that signal it: "running", "cumulative", "so far", "rolling", "previous", "next", "since last".
These are window functions with no GROUP BY. Each input row stays in the output, and the function looks at a neighbourhood of other rows.
The shape of the query
select ...,
sum(x) over (partition by <group> order by <time>
rows between unbounded preceding and current row) as running,
lag(x) over (partition by <group> order by <time>) as previous
from ...;Step by step:
- Reduce to the grain you want to accumulate over (usually one row per day or per month). Windows run over rows, so duplicate days will give odd frames.
PARTITION BYrestarts the calculation per group, for example per account.ORDER BYinsideOVERdefines what "before" means.- The frame (
ROWS BETWEEN ...) defines how far back to look.
with daily as (
select account_id, posted_at::date as day, sum(amount) as net
from transactions
where account_id = 1
group by account_id, posted_at::date
)
select day, net,
sum(net) over (order by day
rows between unbounded preceding and current row) as balance_change_to_date
from daily
order by day
limit 10;A 7-row moving average and the gap since the previous row:
with daily as (
select played_at::date as day, count(*) as plays
from plays
group by played_at::date
)
select day, plays,
round(avg(plays) over (order by day rows between 6 preceding and current row), 1) as avg_7_rows,
plays - lag(plays) over (order by day) as change_vs_prev_row,
day - lag(day) over (order by day) as days_since_prev_row
from daily
order by day
limit 10;Traps interviewers look for
- Frames that quietly change. If you write
order by daywithout a frame, the default isRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. With duplicatedayvalues, tied rows get the same running total. WriteROWSexplicitly. - Missing days.
6 precedingmeans six rows, not six days. If a day has no data, the window stretches over more calendar time. Build a date spine first, or use aRANGEframe with an interval where your database supports it. - Short windows at the start. The first six rows of a 7-day average have fewer than seven inputs. Say whether to show them, hide them, or return NULL until the window is full.
- The first
LAGis NULL.lag(x)has nothing to look at for the first row of each partition. Use the third argument (lag(x, 1, 0)) orCOALESCEonly if zero is truly right. Often NULL is the honest answer. - Forgetting
PARTITION BY. Without it, the last row of one customer feeds the first row of the next. - Window in
WHERE. You cannot filter on a window result in the same query. Wrap it in a CTE.
Variations
- Running count or share.
count(*) over (...), or running sum divided bysum(x) over ()for cumulative percent of total. LEAD. Looks forward. Good for "time until the next event" and for closing intervals.- Offsets.
lag(x, 7)compares with seven rows back, which is week over week on a daily table with no gaps. FIRST_VALUEandLAST_VALUE.last_valueneeds a frame that reaches the end of the partition, or it just returns the current row.- Reset on a condition. Running totals that restart (sessions, streaks) need a group id built first. See the gaps and islands lesson.
In other warehouses
- Snowflake, BigQuery, SQL Server (2012 and later), MySQL (8 and later) and Databricks all support
ROWS BETWEENframes,LAGandLEAD. - BigQuery and SQL Server do not accept
day - lag(day)on dates the way PostgreSQL does. UseDATE_DIFF(day, lag(day) over (...), DAY)in BigQuery andDATEDIFF(day, ..., day)in SQL Server. - SQL Server
RANGEframes only support unbounded and current row, so useROWS. - Snowflake and BigQuery can use
QUALIFYto filter on a window result without a CTE.