Window Functions

Rank, deduplicate, compute running totals, compare rows with LAG and LEAD, and solve gaps-and-islands problems with window functions.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Advanced SQL: CTEs, Subqueries and Set Logic

Window functions compute a value for each row using a set of related rows, without collapsing them like GROUP BY does. They are the most common topic in data engineering SQL rounds.

Syntax

function() OVER (PARTITION BY ... ORDER BY ... ROWS BETWEEN ...)

  • PARTITION BY splits rows into groups (per customer, per city).
  • ORDER BY defines order inside each group.
  • The frame (ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) controls which rows are included.

The functions you must know

  • ROW_NUMBER, RANK, DENSE_RANK: know how each handles ties.
  • LAG and LEAD: compare with previous or next row (days since last order).
  • SUM, AVG, COUNT as windows: running totals and moving averages.
  • FIRST_VALUE, LAST_VALUE, NTILE.

Classic patterns

  • Deduplicate: ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC) = 1 keeps the latest version of each record. You will use this in almost every pipeline.
  • Top N per group: top 3 restaurants per city by orders.
  • Gaps and islands: find streaks of consecutive active days by subtracting a row number from the date.
  • Sessionisation: start a new session when the gap since the previous event exceeds 30 minutes.

Pitfalls

  • LAST_VALUE returning the current row because the default frame ends at the current row.
  • Non-deterministic ordering: ties in ORDER BY give different results between runs. Add a tiebreaker column.
  • Filtering on a window result in WHERE; wrap it in a CTE or use QUALIFY where supported.

You are ready to move on when you can solve top-N-per-group, latest-record dedup and a consecutive-days streak problem in under ten minutes each.

Key concepts

  • PARTITION BY and ORDER BY
  • Window frames
  • ROW_NUMBER, RANK, DENSE_RANK
  • LAG and LEAD
  • Running totals and moving averages
  • Latest-record deduplication
  • Gaps and islands
  • Sessionisation
  • QUALIFY clause: Snowflake, BigQuery, Databricks

Mini project

Using a table of user login events, write queries for: the latest login per user, each user's longest streak of consecutive login days, 7-day moving average of daily active users, and sessions with a 30-minute inactivity gap.

Check yourself

Two orders for the same customer have the same timestamp. How do ROW_NUMBER, RANK and DENSE_RANK each treat them, and why does that matter for deduplication?

Free resources