KatInterview

Master SQL Window Functions: Ranking, Running Totals, and Gap-Fill

SQL & DataModel answer
MediumModel answerSQL & Datawindow-functionsrankingrunning-total

Last 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 (NULL for 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.