row_number / rank
"The top 3 products in each category", "each customer's first order": these need a rank within a group, while keeping every row. Window functions do that. This lesson shows what a window is, how row_number, rank and dense_rank treat ties, and the top-N-per-group pattern interviews love.
Step 1 · PySpark functions · Silver · Window functions, lesson 1 of 2
On this page
Show code in
Every code block on the page follows this.
Read first: groupBy + agg · orderBy (skip if you know them)
In plain words first
Think of a school sports day. Every race has its own finishing order: first, second, third. You do not rank all the children in the school against each other; you rank them within their own race, and nobody leaves the list.
A window is the race: rows grouped by a key (partitionBy), in an order (orderBy). row_number hands out the places, and unlike groupBy, every row stays.
What a window is
groupBy turns each group into one row. A window keeps every row and adds a column computed over that row's group, called its partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more →, in a given order. You define it once with Window.partitionBy(...).orderBy(...) and apply functions with .over(w).
groupBy + agg
Window function
Three ways to number rows
Ranking players by points within each team. Bo and Cy tie on 85:
| player | points | row_number | rank | dense_rank |
|---|---|---|---|---|
| Ana | 90 | 1 | 1 | 1 |
| Bo | 85 | 2 | 2 | 2 |
| Cy | 85 | 3 | 2 | 2 |
| Di | 70 | 4 | 4 | 3 |
- row_number always counts 1, 2, 3, 4. For the tie it picks an order arbitrarily: Bo could be 3 tomorrow.
- rank gives ties the same rank and skips the next numbers, like a sports ranking: two second places, then fourth.
- dense_rank gives ties the same rank without gaps: 1, 2, 2, 3.
Run the example
Input: scores
| player | team | points |
|---|---|---|
| Ana | Red | 90 |
| Bo | Red | 85 |
| Cy | Red | 85 |
| Di | Red | 70 |
| Ed | Blue | 95 |
| Fay | Blue | 60 |
from pyspark.sql import functions as F from pyspark.sql.window import Window w = Window.partitionBy("team").orderBy(F.col("points").desc()) result = scores.select( "team", "player", "points", F.row_number().over(w).alias("row_number"), F.rank().over(w).alias("rank"), F.dense_rank().over(w).alias("dense_rank"), )
SELECT team, player, points, ROW_NUMBER() OVER w AS row_number, RANK() OVER w AS rank, DENSE_RANK() OVER w AS dense_rank FROM scores WINDOW w AS (PARTITION BY team ORDER BY points DESC)
Top N per group
The classic interview pattern: rank inside each group, then filter. The ranking function you choose decides what happens at the cut-off.
Input: scores
| player | team | points |
|---|---|---|
| Ana | Red | 90 |
| Bo | Red | 85 |
| Cy | Red | 85 |
| Di | Red | 70 |
| Ed | Blue | 95 |
| Fay | Blue | 60 |
from pyspark.sql import functions as F from pyspark.sql.window import Window w = Window.partitionBy("team").orderBy(F.col("points").desc()) result = (scores .withColumn("r", F.dense_rank().over(w)) .filter(F.col("r") <= 2))
SELECT * FROM ( SELECT *, DENSE_RANK() OVER ( PARTITION BY team ORDER BY points DESC) AS r FROM scores) WHERE r <= 2
| Question asks for | Use |
|---|---|
| Exactly N rows per group | row_number, with a tiebreaker in the order |
| Everyone in the top N positions, ties included | rank |
| The top N distinct values | dense_rank |
Under the hood Optional deep dive
A window needs all rows of a partition together and sorted. Spark shufflesshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → by the partition keys, then sorts each partition by the partition and order keys, then streams through the sorted rows. In the plan: Exchange hashpartitioning(team) → Sort → Window.
partitionBy moves every row to a single partition, and one tasktask: The work for one partition in one stage, run on one CPU core. Learn more → does all the work. Spark warns "No Partition Defined for Window operation!". On big data that is a guaranteed slow job or out-of-memory error.Several window functions over the same window spec share one shuffle and one sort, so computing row_number, rank and lag together is cheap. A different partitionBy means another shuffle.
Common mistakes
- Using row_number when ties matter — One of the tied rows is dropped arbitrarily at the cut-off. Use rank or dense_rank, or add a tiebreaker.
- A window without partitionBy — All rows go to one task. Partition by something, or compute a global rank another way.
- Expecting the window order to order the output — The orderBy inside the window only orders rows within each partition for the function. Sort the result separately if you need it.
Key takeaways
- Window functions keep every row and add a value computed over its partition.
row_numberhas no ties,rankleaves gaps,dense_rankdoes not.- Top N per group is rank-then-filter; choose the function by how ties should behave.
- A window costs a shuffle and a sort; always partition it.
Interview prep
THE QUESTION
"Find the second highest salary in each department."
dense_rank over partitionBy("dept").orderBy(desc("salary")) and filter rank 2. Explain why dense_rank: if two people share the top salary, rank would skip 2 and return nothing, and row_number would return the other top earner. Interviewers listen for that tie discussion.Avoid: using row_number. With ties at the top, "second highest" is a different person, not the second highest salary.
Follow-ups · answer out loud, then open
Follow-up"How do rank, dense_rank and row_number differ on ties of 100, 100, 90?"
Scenario"Keep the latest record per order, where two records share the latest timestamp."
Trap"A window with orderBy but no partitionBy is fine on a big table."
Check yourself
3 questionsValues in order are 100, 90, 90, 80. What does rank() give the 80?
Show the answer
4. rank gives the two 90s rank 2 and skips 3, so 80 is 4th. dense_rank would give 3.
You need exactly one row per customer: their latest order. Which function?
Show the answer
row_number with a tiebreaker. row_number guarantees one row per partition; a tiebreaker in the order makes the choice deterministic.
What happens with Window.orderBy("ts") and no partitionBy on a 1 TB table?
Show the answer
All rows are moved to one partition and processed by one task. Without partition keys the whole dataset is one window partition, so one task processes everything.
Practise this
Problems that use row_number / rank, graded on hidden tests
- Latest Order per CustomerWindow Functions Medium
- Running Total by RegionWindow Functions Medium
- Top Two Salary Levels per DepartmentWindow Functions Medium
Keep going
Up next · Window functions · lesson 2 of 2 · 4 min readlag / lead
Read the previous or next row in a window to compute changes, gaps and streaks.
Related lessons
Previous: spark.sql and temp views
Primary sources: functions.row_number · Window functions (SQL)