Top category in each city
We reuse city_category (revenue per city and category) from lesson 3:
from pyspark.sql import Window
by_city = Window.partitionBy("city").orderBy(F.desc("revenue"))
(city_category
.withColumn("rank", F.rank().over(by_city))
.filter(F.col("rank") == 1)
.show())+---------+-----------+---------+----+
| city| category| revenue|rank|
+---------+-----------+---------+----+
|Bengaluru|Electronics|906941.00| 1|
| Delhi|Electronics|915309.00| 1|
| Kolkata|Electronics|767170.00| 1|
| Mumbai|Electronics|762955.00| 1|
| Pune| Fashion|691580.00| 1|
+---------+-----------+---------+----+partitionBy("city") restarts the ranking for each city; orderBy(F.desc("revenue")) decides who's first. Electronics wins everywhere except Pune, where Fashion leads.
row_number vs rank vs dense_rank
scores = spark.createDataFrame([("A", 300), ("B", 200), ("C", 200), ("D", 100)], ["product", "units"])
w = Window.orderBy(F.desc("units"))
scores.select("product", "units",
F.row_number().over(w).alias("row_number"),
F.rank().over(w).alias("rank"),
F.dense_rank().over(w).alias("dense_rank")).show()+-------+-----+----------+----+----------+
|product|units|row_number|rank|dense_rank|
+-------+-----+----------+----+----------+
| A| 300| 1| 1| 1|
| B| 200| 2| 2| 2|
| C| 200| 3| 2| 2|
| D| 100| 4| 4| 3|
+-------+-----+----------+----+----------+B and C tie on 200 units. Pick the function by the question you're answering:
| Function | Ties | Use for |
|---|---|---|
| row_number | Different numbers | Exactly one row per group (latest, first) |
| rank | Same number, then a gap | Competition-style ranking, top N including ties |
| dense_rank | Same number, no gap | Nth highest value (e.g. 2nd highest salary) |
De-duplicate: keep the latest row
# The app sometimes sends the same order twice with a newer status
updates = spark.createDataFrame(
[(100002, "DELIVERED", "2026-10-01 16:05:15"), (100002, "RETURNED", "2026-10-09 11:00:00"),
(100003, "DELIVERED", "2026-10-01 12:00:00")],
["order_id", "status", "updated_at"])
latest_first = Window.partitionBy("order_id").orderBy(F.desc("updated_at"))
(updates
.withColumn("rn", F.row_number().over(latest_first))
.filter("rn = 1")
.drop("rn")
.show())+--------+---------+-------------------+
|order_id| status| updated_at|
+--------+---------+-------------------+
| 100002| RETURNED|2026-10-09 11:00:00|
| 100003|DELIVERED|2026-10-01 12:00:00|
+--------+---------+-------------------+Order 100002 arrived twice; the newer status (RETURNED) won. This is the most common window function in real pipelines, the same idea as QUALIFY ROW_NUMBER() = 1 in our Snowflake course.
lag, moving average, running total
daily = (delivered.groupBy("order_date").agg(F.sum("amount").alias("revenue")))
w_time = Window.orderBy("order_date")
w_7 = w_time.rowsBetween(-6, 0)
(daily
.withColumn("prev_day", F.lag("revenue").over(w_time))
.withColumn("change_pct", F.round((F.col("revenue") / F.col("prev_day") - 1) * 100, 1))
.withColumn("avg_7d", F.round(F.avg("revenue").over(w_7), 0))
.withColumn("running_total", F.sum("revenue").over(w_time.rowsBetween(Window.unboundedPreceding, 0)))
.filter(F.col("order_date").between("2026-10-18", "2026-10-22"))
.orderBy("order_date")
.show())+----------+---------+---------+----------+------+-------------+
|order_date| revenue| prev_day|change_pct|avg_7d|running_total|
+----------+---------+---------+----------+------+-------------+
|2026-10-18|165515.00|126841.00| 30.5|141455| 2682182.00|
|2026-10-19|172199.00|165515.00| 4.0|146222| 2854381.00|
|2026-10-20|298942.00|172199.00| 73.6|172453| 3153323.00|
|2026-10-21|272134.00|298942.00| -9.0|190554| 3425457.00|
|2026-10-22|211494.00|272134.00| -22.3|200706| 3636951.00|
+----------+---------+---------+----------+------+-------------+Diwali week in numbers: revenue jumped 73.6% on 20 October, the 7-day average climbed from ₹1.41 lakh to ₹2.0 lakh, and the running total passed ₹36 lakh by the 22nd. Note the filter comes after the window columns: filtering first would make the averages see only five days (a classic bug).
| Function | Gives |
|---|---|
| lag(col, n) / lead(col, n) | Value n rows before / after |
| first / last | First or last value in the window |
| sum / avg / min / max over a window | Running or moving aggregates |
| rowsBetween(start, end) | Frame by row count (-6, 0 = last 7 rows) |
| rangeBetween(start, end) | Frame by value range (e.g. by days on a numeric date) |
| ntile(n), percent_rank | Buckets and percentiles |
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1Difference between groupBy and a window function?Fresher+
Q2How do you find the second highest salary per department?1–3 yrs+
Q3How do you remove duplicates keeping the latest record?1–3 yrs+
Q4A window function job is very slow. Why?3+ yrs+
Key takeaways
- ✓Windows rank, compare and accumulate without losing rows.
- ✓row_number for de-duplication is the pattern you'll use most.
- ✓Choose rank vs dense_rank by how you want ties handled.
- ✓Always give big windows a partitionBy.
Frequently asked questions
What is a window function?
A calculation across a group of related rows that keeps every row, unlike groupBy which collapses them. Examples: rank within a city, the previous day's value, a running total.
row_number, rank or dense_rank?
row_number gives unique numbers (ties broken arbitrarily or by more sort columns): use it to pick exactly one row. rank gives ties the same number and skips the next (1, 2, 2, 4). dense_rank doesn't skip (1, 2, 2, 3).
Why use row_number instead of dropDuplicates?
dropDuplicates keeps an arbitrary row per key. row_number ordered by updated_at descending keeps exactly the latest one, which is what pipelines need.
Are window functions expensive?
A window with partitionBy shuffles by those columns and sorts within each partition. A window with no partitionBy moves all rows into ONE partition: fine for small daily summaries, a disaster on big data.
🧠 Quick check: window functions
1. Keep only the latest version of each order. Use...
2. Units 300, 200, 200, 100. dense_rank gives...
3. lag('revenue') returns...
4. rowsBetween(-6, 0) means...
Checking your access…