Master SQL Window Functions: Ranking, Running Totals, and Gap-Fill
SQL & DataModel answerLast updated
Write analytical SQL queries using only window functions — no self-joins — to compute running totals, forward-fill sparse events, and rank users within groups.
Context
You're working with two tables that track user payments and subscription lifecycle events:
payments(user_id INT, payment_date DATE, amount NUMERIC)
subscription_events(user_id INT, event_date DATE, event_type TEXT, plan TEXT)
-- event_type is one of: 'start', 'upgrade', 'downgrade', 'cancel'
-- plan is NULL when event_type = 'cancel'
The constraint: every computation that would normally require looking at other rows — previous values, running totals, ranks — must use a window function. No self-joins allowed.
Tasks
Work through each part in order. For each query, briefly explain your choices before writing SQL.
Part 1 — Running total and gap between payments
For each payment row, compute:
- The cumulative amount spent by that user up to and including the current row
- The number of days since that user's previous payment (
NULLfor their first)
What happens when a user has two payments on the same date? How do you handle it?
Part 2 — Forward-fill the active plan
subscription_events has a NULL plan on cancel rows. For every row, add a column filled_plan that shows the most recent non-null plan for that user. Also add a days_in_state column showing how long the user stayed in each state before the next event.
What does a cancel row mean for filled_plan? State your assumption explicitly.
Part 3 — Top 3 spenders per calendar month
Aggregate payments to monthly totals per user, then label each user's rank within their month. Return all users whose rank is 3 or better.
How do RANK, DENSE_RANK, and ROW_NUMBER differ here? Which one should you pick, and why?
Part 4 — Month-over-month change and share of monthly spend
From the monthly aggregates, compute:
- Each user's spend change versus the prior month
- Each user's spend as a fraction of that month's total across all users
What goes wrong if a user skips a month? How would you detect or fix it?
What's expected
- Correct, runnable SQL for each part (Postgres syntax is fine; note dialect differences where they matter)
- A brief explanation of each key decision — frame type, tiebreaker, ranking function choice
- Identification of edge cases and how your query handles them
Hints
Hint 1
For the running total, the default window frame under ORDER BY is RANGE UNBOUNDED PRECEDING, which groups same-date rows together. Switch to ROWS UNBOUNDED PRECEDING and add a tiebreaker column to ORDER BY to make the result deterministic row-by-row.
Hint 2
To forward-fill a sparse column, COUNT(col) OVER (...) only increments when col is non-null, so it naturally creates group IDs you can then MAX or FIRST_VALUE over — no IGNORE NULLS support needed.
Hint 3
You cannot filter on a window function alias (like rnk <= 3) in the same SELECT where you define it, because window functions are evaluated after WHERE. Wrap the ranking in a CTE or subquery first, or use QUALIFY if your dialect supports it.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Window functions let you reference neighboring rows without collapsing the result set and without the O(n²) cost of a self-join. The key is matching the right tool to the right need:
| Need | Window tool |
|---|---|
| Cumulative sum | SUM(...) OVER (PARTITION BY ... ORDER BY ... ROWS UNBOUNDED PRECEDING) |
| Previous / next row value | LAG / LEAD |
| Forward-fill sparse column | COUNT(col) group trick, then MAX within group |
| Rank within a partition | RANK / DENSE_RANK / ROW_NUMBER |
Always state upfront: which dialect, whether duplicate-date payments exist, and whether amounts can be negative (refunds).
Part 1: Running Total and Days Between Payments
SELECT
user_id,
payment_date,
amount,
SUM(amount) OVER (
PARTITION BY user_id
ORDER BY payment_date, amount -- tiebreaker makes ordering deterministic
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total,
payment_date - LAG(payment_date) OVER (
PARTITION BY user_id ORDER BY payment_date, amount
) AS days_since_prev_payment
FROM payments;
ROWS vs RANGE: The default frame under ORDER BY is RANGE UNBOUNDED PRECEDING, which treats same-date rows as peers and assigns them the combined total at once. ROWS advances one physical row at a time, which is almost always what "running" means. Adding amount (or a surrogate key like payment_id) to ORDER BY makes the result stable across executions.
Date arithmetic by dialect:
- Postgres:
date - date→ integer days - BigQuery:
DATE_DIFF(d1, d2, DAY) - Snowflake:
DATEDIFF('day', d2, d1)
The first payment returns NULL for days_since_prev_payment. Leave it as-is, or COALESCE to 0 if the consumer requires it.
Part 2: Forward-Fill the Active Plan
Most engines don't support LAST_VALUE(... IGNORE NULLS). The portable two-step:
COUNT(plan) OVER (...)increments only on non-null values, creating a group counter.MAX(plan)within each(user_id, group_counter)returns the one non-null value for that group.
WITH grp AS (
SELECT
*,
COUNT(plan) OVER (
PARTITION BY user_id
ORDER BY event_date
ROWS UNBOUNDED PRECEDING
) AS plan_grp
FROM subscription_events
)
SELECT
user_id,
event_date,
event_type,
plan,
MAX(plan) OVER (PARTITION BY user_id, plan_grp) AS filled_plan,
LEAD(event_date) OVER (PARTITION BY user_id ORDER BY event_date)
- event_date AS days_in_state
FROM grp;
Assumption to state: a cancel row carries the last known plan in filled_plan (useful for "what plan did they churn from"). If the business wants filled_plan reset to NULL on cancel, add a CASE on event_type.
Where supported (Snowflake, BigQuery, Oracle), the shorter form is:
LAST_VALUE(plan IGNORE NULLS) OVER (
PARTITION BY user_id ORDER BY event_date ROWS UNBOUNDED PRECEDING
) AS filled_plan
Part 3: Top 3 Spenders per Month
WITH monthly AS (
SELECT
DATE_TRUNC('month', payment_date) AS month,
user_id,
SUM(amount) AS spend
FROM payments
GROUP BY 1, 2
),
ranked AS (
SELECT
*,
RANK() OVER (PARTITION BY month ORDER BY spend DESC) AS rnk,
DENSE_RANK() OVER (PARTITION BY month ORDER BY spend DESC) AS drnk,
ROW_NUMBER() OVER (PARTITION BY month ORDER BY spend DESC, user_id) AS rn
FROM monthly
)
SELECT month, user_id, spend, rnk
FROM ranked
WHERE rnk <= 3
ORDER BY month, rnk, user_id;
Ranking function comparison for spends of 100, 100, 90:
| Function | Assigned ranks | Use when |
|---|---|---|
RANK | 1, 1, 3 | Ties share a place; gaps follow |
DENSE_RANK | 1, 1, 2 | Every spend level gets a consecutive rank |
ROW_NUMBER | 1, 2, 3 | Exactly N rows; requires explicit tiebreaker |
"Top 3 spenders" is ambiguous. Clarify: if two users tie for 3rd, does the business want both included (RANK or DENSE_RANK) or only one (ROW_NUMBER)? In a competition context, RANK is natural. For a fixed-size leaderboard, ROW_NUMBER with user_id as tiebreaker is predictable.
Why the CTE is necessary: window functions are evaluated after GROUP BY and WHERE, so WHERE rnk <= 3 can't reference a column defined in the same SELECT. A CTE (or subquery) resolves this. In Snowflake, BigQuery, and Databricks you can use QUALIFY rnk <= 3 directly.
Part 4: Month-over-Month Change and Share of Total
SELECT
month,
user_id,
spend,
spend - LAG(spend) OVER (PARTITION BY user_id ORDER BY month) AS mom_change,
spend / SUM(spend) OVER (PARTITION BY month) AS share_of_month
FROM monthly;
The skipped-month pitfall: LAG returns the previous row that exists, not the previous calendar month. If a user skips February, March's mom_change computes March minus January — silently wrong. Fix it by checking:
CASE
WHEN LAG(month) OVER (PARTITION BY user_id ORDER BY month)
= month - INTERVAL '1 month'
THEN spend - LAG(spend) OVER (PARTITION BY user_id ORDER BY month)
ELSE NULL -- or flag as non-consecutive
END AS mom_change
A complete solution generates a full month spine and left-joins onto it, but that requires a join — worth naming as the trade-off if the interviewer asks.
Complexity
- Time: O(n log n) per distinct window specification (one sort pass per unique
OVERclause). Windows sharing the samePARTITION BY / ORDER BYcan reuse the sort. - Space: O(n) for sort buffers and frame state.
- A self-join on "all prior rows" is O(n²) per partition — the real reason window functions exist.
Common Mistakes
- Using
RANGEinstead ofROWSfor running sums, causing ties to get the same cumulative value. - Missing a tiebreaker in
ORDER BY, producing non-deterministic output. - Filtering on a window alias in the same
SELECTwhere it's defined. - Assuming
LAGbridges calendar gaps — it doesn't. - Forgetting
NULLpropagation:LAGon the first row,LEADon the last, andCOUNTignoring nulls (which is the forward-fill trick's whole mechanism).