Skip to main content
Intermediatehow it works Verified ~9 min

What are window functions in PySpark and how do you use them? Show a running total and the latest order per customer.

Source: PySpark documentation

Quick answer

A window function computes a value for each row from a related group of rows without collapsing them. Define Window.partitionBy(key).orderBy(col), then apply row_number(), lag() or an aggregate with a frame, such as rowsBetween(Window.unboundedPreceding, Window.currentRow) for a running total.

What a window function does

A groupBy collapses rows into one per group. A window function keeps every row and adds a value computed from a window of related rows. A window spec has three parts:

  • partitionBy(...): the group (for example, customer).
  • orderBy(...): the order inside the group.
  • an optional frame: which rows around the current row are included.
main.py
from pyspark.sql import Window, functions as F

w = Window.partitionBy("customer_id").orderBy(F.col("order_ts").desc())

latest = (orders
    .withColumn("rn", F.row_number().over(w))
    .filter("rn = 1")
    .drop("rn"))                      # latest order per customer

Other tools: rank(), dense_rank(), lag("amount", 1), lead(...), sum("amount").over(w).

The default frame gotcha

When you add orderBy, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Rows with the same ordering value (ties) are treated as one group, so they all get the same running total. Without orderBy the frame is the whole partition.

Example data with a tie on day 2:

dayamountsum default (RANGE)sum with rowsBetween(unboundedPreceding, currentRow)
1101010
2206030
2306060
340100100

I checked these numbers with SQL window functions (same frame rules). For a true row-by-row running total, set the frame explicitly:

main.py
w_run = (Window.partitionBy("customer_id")
               .orderBy("day", "order_id")                       # add a tiebreaker
               .rowsBetween(Window.unboundedPreceding, Window.currentRow))

orders.withColumn("running_total", F.sum("amount").over(w_run))

Ranking functions on ties

FunctionValues for scores 100, 90, 90, 80
row_number()1, 2, 3, 4
rank()1, 2, 2, 4
dense_rank()1, 2, 2, 3

Use row_number() when you need exactly one row per group (latest order); add a tiebreaker column so the result is deterministic.

Performance

A window with partitionBy triggers a shuffle by that key and a sort inside each partition. A window without partitionBy moves all data into one partition and warns about performance, so avoid it on large data. A very skewed key makes one task slow.

Animated explanation
  1. 1WindowpartitionBy(customer).orderBy(ts desc)
  2. 2row_number()numbers rows in each partition
  3. 3No collapseevery row kept
  4. 4Filterrow 1 = latest order per customer
Window functions add a value per row instead of grouping rows away.
See the concept: Spark shufflegroupBy moves every record to the partition that owns its key
Spark shuffle: groupBy(key)
key A key B key C

Input partition 0

ACBA

Input partition 1

BBCA

Input partition 2

CABC

Stage 1: narrow transformations run in place

Before: each input partition holds a mix of keys. After the shuffle, all records with the same key live in one partition. That data movement over the network is what makes wide transformations expensive.

Key points

  • A window function adds a computed column without collapsing rows.
  • Spec = partitionBy + orderBy + optional frame.
  • With orderBy, the default frame is RANGE UNBOUNDED PRECEDING to CURRENT ROW, so ties get the same running value.
  • Use rowsBetween plus a tiebreaker column for a row-by-row running total.
  • row_number() = 1 is the standard "latest row per key" pattern.

Common mistakes

  • Expecting a running total to increase on every row when the order column has ties.
  • Using a window without partitionBy on a large DataFrame.
  • Picking rank() when exactly one row per group is needed.
  • Ordering by a non-unique column with row_number() and getting non-deterministic results.

Prerequisites

  • DataFrame groupBy
  • Shuffle and partitions

Best practices

  • Add a unique tiebreaker to orderBy for deterministic results.
  • Set the frame explicitly for running aggregates.
  • Filter early to reduce shuffled data, and watch skew on the partition key.
  • Check explain() for the Window node and the Exchange before it.

Likely follow-ups

  • What is the difference between rowsBetween and rangeBetween?
  • What is the difference between row_number, rank and dense_rank?
  • How would you compute a 7-day moving average with a window function?
  • Why is a window without partitionBy a performance problem?
  • How would you get the second highest salary per department with a window?

References

Discussion