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

max_by / min_by

Return the value from the row where another column is largest, or smallest, in each group. One aggregate instead of a window, a row number and a filter.

Step 1 · PySpark functions · Silver · Smarter aggregates, lesson 1 of 2

Read first: groupBy + agg · row_number / rank (skip if you know them)

In plain words first

At a race you do not only want the fastest time; you want the name of the runner who ran it. max_by answers "who had the biggest value?" in one step: for each group it finds the row with the largest value in one column and hands back another column from that same row.

What it does

max_by(page, ts) finds the row with the largest ts in each group and returns that row's page. min_by does the same for the smallest. It is often called argmax.

Step by step

pageviews

session_idpagets
s1/home10:00
s1/pricing10:02
s1/checkout10:05
s2/search11:00
s2/product/4211:01

max_by(page, ts)

session_idexit
s1/checkout
s2/product/42
  1. 1
    Spark splits the rows into groups by session_id.
  2. 2
    For each group it keeps one running pair: the largest ts seen so far and the page from that row.
  3. 3
    Each new row either replaces the pair, if its ts is larger, or is ignored.
  4. 4
    When the group ends, Spark returns the page half of the pair. No sorting happens at any point.

Run the example

PySparkSpark SQL

Input: pageviews

session_idpagets
s1/home10:00
s1/pricing10:02
s1/checkout10:05
s2/search11:00
s2/product/4211:01
s3/home12:00
from pyspark.sql import functions as F
result = pageviews.groupBy("session_id").agg(
    F.min_by("page", "ts").alias("entry"),
    F.max_by("page", "ts").alias("exit"),
)
SELECT session_id,
       min_by(page, ts) AS entry,
       max_by(page, ts) AS exit
FROM pageviews
GROUP BY session_id

Without it

The usual workaround ranks rows in a window and keeps the first one: three steps and a sort for a single value.

PySparkSpark SQL
from pyspark.sql import functions as F
from pyspark.sql.window import Window
w = Window.partitionBy("session_id").orderBy(F.desc("ts"))
(pageviews.withColumn("pos", F.row_number().over(w))
    .filter("pos = 1").select("session_id", "page"))
SELECT session_id, page
FROM (
  SELECT *, ROW_NUMBER() OVER (
    PARTITION BY session_id ORDER BY ts DESC) AS pos
  FROM pageviews)
WHERE pos = 1

Performance Optional deep dive

max_byrow_number window
Before the shuffleshuffle: 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 →Partial aggregationaggregate: A function that turns many rows into one value per group: count, sum, avg, min, max. Learn more →: one row per group per 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 →Nothing: every row is shuffled
SortingNoneSorts every row by group and time
Physical planHashAggregate → Exchange → HashAggregateExchange → Sort → Window → Filter

With many rows per group, max_by moves far less data across the network. The window version is still right when you need the top N rows, or the whole winning row with many columns and a defined tie rule.

Several columns from the winning row

Calling max_by once per column is fine when the ordering column is unique. With ties, each call can pick a different row. Pack the columns into one structstruct: A column that holds a small record with named fields, like an address with a city and a pin code. Learn more → so they always come from the same row:

PySparkSpark SQL
pageviews.groupBy("session_id").agg(
    F.max_by(F.struct("page", "referrer"), "ts").alias("last")
).select("session_id", "last.page", "last.referrer")
SELECT session_id, last.page, last.referrer
FROM (
  SELECT session_id, max_by(struct(page, referrer), ts) AS last
  FROM pageviews GROUP BY session_id)

An older trick does the same without max_by: max(struct(ts, page)). Structs compare field by field, so the maximum struct is the one with the latest ts, and you read .page from it.

Common mistakes

  • Ignoring ties — If two rows share the largest ts, either value can come back, and it can differ between runs. Make the ordering column unique or add a tiebreaker.
  • Expecting nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → ordering values to count — Rows with a null ts are skipped. A group with only null ts returns null.
  • Using F.max_by on PySpark before 3.3 — Use F.expr("max_by(page, ts)"); the SQL function exists since 3.0.

Key takeaways

  • max_by(x, ord) returns x from the row with the largest ord in each group.
  • It aggregates before the shuffle and never sorts, so it beats the window version for "top 1".
  • Ties are not deterministic, and nulls in ord are skipped.
  • Use a struct to take several columns from the same row.

Interview prep

THE QUESTION

"Find the last page of each session."

Most candidates write the window version. Offer max_by, explain that it aggregates before the shuffle and never sorts, then mention the tie gotcha unprompted, and the struct trick for several columns.

Avoid: only the row_number window version. It works, but max_by is one aggregate with no sort.

Follow-ups · answer out loud, then open

Follow-up"What does max_by return when two rows tie on the ordering column?"
One of their values, and which one is not deterministic. If ties are possible, order by a struct that includes a tiebreaker: F.max_by("page", F.struct("ts", "event_id")).
Scenario"Return the last page and the last referrer of each session together."
F.max_by(F.struct("page", "referrer"), "ts"), then select the struct's fields. Two separate max_by calls could pick different rows when there are ties.
Trap"max_by ignores rows where the value is null."
It ignores rows where the ordering column is null, but it can return a null value if the row with the largest ordering value has a null in the value column.

Check yourself

3 questions

Two rows in session s9 share the latest ts. What does max_by(page, ts) return for s9?

Show the answer

One of the two pages, and which one is not guaranteed. max_by keeps whichever tied row it meets first, and the order depends on partitioning. Add a tiebreaker to make it deterministic.

Why is max_by usually cheaper than row_number() over a window for "latest row per group"?

Show the answer

It aggregates before the shuffle and never sorts. Each partition reduces its rows to one pair per group before the exchange, and no sort is needed. The window shuffles and sorts every row.

How do you get page and referrer guaranteed from the same winning row?

Show the answer

max_by(struct(page, referrer), ts). One max_by over a struct picks a single row and returns all its fields together.

Practise this

Problems that use max_by / min_by, graded on hidden tests

See all 4 problems →

Keep going

Up next · Smarter aggregates · lesson 2 of 2 · 4 min read
percentile_approx
Medians and p90s that scale to billions of rows, and how the accuracy setting trades memory for error.

Related lessons

Previous: lag / lead

Primary sources: functions.max_by · Built-in functions (SQL)