Window Functions (ROW_NUMBER, RANK, DENSE_RANK)
Rank and number rows over partitions without collapsing the grain of the table.
In plain words
Window functions number or rank rows within groups while keeping every row, so you can easily pick the first, latest or top few in each group.
Think of it like…
A race results sheet kept separately for each category (PARTITION BY) and sorted by finish time: position 1, 2, 3 within each category, without merging the categories. Ties may share a position (RANK) or each get their own (ROW_NUMBER).
Where you’ve seen it
A customer table has one row per status change (about 6 million rows for 1.2 million customers). To get the current status as of the snapshot date, the analyst writes SELECT * FROM (SELECT s.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY changed_at DESC, status_id DESC) AS rn FROM status_history s WHERE changed_at <= :snapshot) t WHERE rn = 1. The filter on changed_at keeps the result point-in-time correct, and the status_id tie-breaker makes the pick deterministic when two changes share a timestamp.
Words you’ll hear
- PARTITION BY
- Restarts the calculation for each group (like GROUP BY, but rows are kept).
- ROW_NUMBER / RANK / DENSE_RANK
- Unique numbers / ties share rank with gaps / ties share rank without gaps.
- NTILE(n)
- Divides each partition into n roughly equal buckets (deciles with n = 10).
- Deterministic ordering
- An ORDER BY with a unique tie-breaker so results are reproducible.
Visual diagram
Theory & deep dive
Ranking functions and their differences
With scores 100, 90, 90, 80, ROW_NUMBER() gives 1, 2, 3, 4 (ties broken arbitrarily unless you add tie-breakers); RANK() gives 1, 2, 2, 4 (ties share, gap after); DENSE_RANK() gives 1, 2, 2, 3 (ties share, no gap). Use ROW_NUMBER for deduplication and "exactly one row" requirements, RANK or DENSE_RANK for leaderboards where ties should share a place, and NTILE for bucketing (NTILE(10) OVER (ORDER BY spend) creates spend deciles; note that bucket sizes differ by at most one row, and tied values can land in different buckets).
You can't filter on a window function in WHERE of the same query, since windows are computed after WHERE; wrap the query in a subquery or CTE and filter the rank there. Some warehouses (Snowflake, BigQuery, DuckDB) offer QUALIFY, which filters on window results directly: SELECT * FROM status_history QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY changed_at DESC) = 1.
SELECT * FROM (SELECT category, product, SUM(amount) AS revenue, DENSE_RANK() OVER (PARTITION BY category ORDER BY SUM(amount) DESC) AS r FROM sales GROUP BY category, product) t WHERE r <= 3; DENSE_RANK keeps ties instead of cutting one arbitrarily.
Dedup, point-in-time and the pandas equivalents
Deduplicate by partitioning on the business key and ordering by the field that decides which row wins (latest update, most complete record): keep rn = 1. Always add a unique tie-breaker (an id) so the same query returns the same rows tomorrow. For point-in-time training data, filter history by <= snapshot_date before ranking so you never pick a row created after the prediction time.
In pandas: df.sort_values(["changed_at", "status_id"]).groupby("customer_id").tail(1) or df.drop_duplicates(subset="customer_id", keep="last") after sorting; df.groupby("category")["revenue"].rank(method="dense", ascending=False) for dense ranks; pd.qcut(df.spend, 10, labels=False) for deciles. Do the heavy lifting in SQL for big tables, and verify uniqueness afterwards: SELECT customer_id FROM result GROUP BY 1 HAVING COUNT(*) > 1 should return nothing.
ROW_NUMBER() OVER (PARTITION BY email ORDER BY updated_at DESC, id DESC) with WHERE rn = 1 keeps the most recent record per email, and the id tie-breaker ensures two rows updated in the same second don't swap between runs.
How it works, step by step
Step 1 of 41. Define the partition and order
Choose the entity key to partition by and the column that decides which row wins.
- Add
- a tie-breaker
When to use it & trade-offs
What it is
A window function computes a value for each row using a set of related rows (the window) without collapsing rows like GROUP BY: ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC). ROW_NUMBER gives unique positions, RANK gives ties the same rank and then skips numbers, DENSE_RANK gives ties the same rank without gaps, and NTILE(n) splits rows into n buckets. These solve the everyday data-science tasks: latest record per entity, deduplication, top-N per group and percentile buckets.
Why it matters: Training tables need exactly one row per entity at a point in time, and raw data has many: multiple status updates per customer, repeated events, several model scores per day. ROW_NUMBER with a clear ordering is the standard way to pick the right row, and choosing the wrong ranking function (or an unstable ORDER BY) gives non-reproducible datasets. It's one of the most common SQL interview topics.
When to reach for it
- Current record per customer as of a snapshot
- Deduplicating events and contacts
- Top-N products or users per group
When to avoid or be careful
- ORDER BY without a unique tie-breaker
- Ranking before filtering out future rows
- RANK where exactly one row is required
Ranking functions
Strengths: Always unique; simple filter rn = 1.
Watch out: Arbitrary among ties unless ordered fully.
Strengths: Respects ties.
Watch out: May return more than N rows with ties.
Strengths: Equal-sized buckets.
Watch out: Ties can split across buckets.
Interview signals & numbers to know
When this topic comes up
- “Get the latest record per user”
- “Top 3 per category”
- “RANK vs DENSE_RANK vs ROW_NUMBER”
- Deduplication
- Point-in-time correctness
Benchmarks & rules of thumb
- 1, 2, 2, 4
- RANK on scores 100, 90, 90, 80
- 1, 2, 2, 3
- DENSE_RANK on the same scores
- 10
- NTILE buckets for deciles
Common mistakes & follow-ups
Common interview mistakes
- Using RANK to deduplicate and keeping two rows for a tie.
- Picking the latest status without filtering to the snapshot date, leaking the future.
- Forgetting a tie-breaker, so training data changes between runs.
Likely interviewer follow-ups
- What's the difference between RANK and DENSE_RANK?
- How do you get the latest row per customer as of a given date?
- Why does a window function need a subquery to filter on its result?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Window Functions (ROW_NUMBER, RANK, DENSE_RANK) with data science interview Q&A and hands-on practice.