Skip to content
Silver 4 min read · Window 3 practice problems ↓

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

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

Many rows in, one row per group out.

Window function

Many rows in, the same rows out, each with a value computed from its partition.

Three ways to number rows

Ranking players by points within each team. Bo and Cy tie on 85:

playerpointsrow_numberrankdense_rank
Ana90111
Bo85222
Cy85322
Di70443
  • 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

PySparkSpark SQL

Input: scores

playerteampoints
AnaRed90
BoRed85
CyRed85
DiRed70
EdBlue95
FayBlue60
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.

PySparkSpark SQL · Top 2 per team

Input: scores

playerteampoints
AnaRed90
BoRed85
CyRed85
DiRed70
EdBlue95
FayBlue60
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 forUse
Exactly N rows per grouprow_number, with a tiebreaker in the order
Everyone in the top N positions, ties includedrank
The top N distinct valuesdense_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.

Watch out: a window with no 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_number has no ties, rank leaves gaps, dense_rank does 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."

Use 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?"
row_number gives 1, 2, 3 (arbitrary between the ties). rank gives 1, 1, 3. dense_rank gives 1, 1, 2.
Scenario"Keep the latest record per order, where two records share the latest timestamp."
row_number over partitionBy order_id, ordered by timestamp descending and then a tiebreaker column (a sequence number or ingestion time). Without the tiebreaker, which of the tied rows survives can change between runs.
Trap"A window with orderBy but no partitionBy is fine on a big table."
It moves every row to a single partition and task to sort it. Spark warns: "No Partition Defined for Window operation". Partition by something, or use a different approach for global ranks.

Check yourself

3 questions

Values 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

See all 8 problems →

Keep going

Up next · Window functions · lesson 2 of 2 · 4 min read
lag / 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)