groupBy & agg

Apache Spark · Aggregations & Joins

Theory

groupBy(cols) collects rows that share the same values in the given columns into groups, and agg(...) computes one summary row per group with aggregate functions such as F.sum, F.count, F.avg, F.min, F.max, F.countDistinct, F.collect_set and F.percentile_approx. Give every result a clear name with .alias(). Calling agg directly on a DataFrame, without groupBy, aggregates the whole table into one row.

groupBy is a wide transformation: Spark first computes partial results in each partition (partial_sum), shuffles them by the group key and then merges them, which is why it scales to billions of rows. There is no separate HAVING method: you filter the aggregated DataFrame afterwards. For example, orders.groupBy('region').agg(F.sum('amount').alias('total'), F.count('*').alias('orders')) gives North 104500 from 3 orders, and .filter('total > 50000') keeps only the big regions.

Why we use it

Totals, counts and averages per customer, region or day are the heart of reporting and feature engineering. groupBy().agg() lets you compute many metrics in a single distributed pass over the data.

When to use it

Use groupBy().agg() whenever you need one row per group. Put all metrics in one agg call instead of several groupBy jobs. Use window functions instead when you need the group total next to every original row rather than one row per group.

How it works

  1. DataFrame of rows
  2. Partial aggregation inside each partition
  3. Shuffle partial results by the group key
  4. Merge partials into one row per group
  5. Is there a HAVING-style condition? Yes: filter() the aggregated rows. No: Keep all groups.
  6. One row per group

Syntax

df.groupBy("k1", "k2").agg(F.sum("x").alias("total"), F.count("*").alias("n"))
df.groupBy("k").count()
df.agg(F.max("x"))                      # whole table
...agg(...).filter(F.col("total") > 100)   # HAVING

Example

from pyspark.sql import SparkSession, functions as F

spark = (SparkSession.builder.master("local[1]")
         .config("spark.ui.enabled", "false")
         .getOrCreate())

orders = spark.createDataFrame([
    (101, 1, "North", "Laptop", 1, 55000.0, "2026-01-05"),
    (102, 2, "West",  "Phone",  2, 30000.0, "2026-01-06"),
    (103, 1, "North", "Mouse",  3,  1500.0, "2026-01-06"),
    (104, 3, "South", "Laptop", 1, 52000.0, "2026-01-07"),
    (105, 4, "West",  "Tablet", 1, 25000.0, "2026-01-08"),
    (106, 2, "East",  "Phone",  1, 15000.0, "2026-01-08"),
    (107, 5, "North", "Tablet", 2, 48000.0, "2026-01-09"),
    (108, 3, "South", "Mouse",  4,  2000.0, "2026-01-10"),
], "order_id INT, customer_id INT, region STRING, product STRING, "
   "qty INT, amount DOUBLE, order_date STRING"
).withColumn("order_date", F.to_date("order_date"))

summary = (orders.groupBy("region")
           .agg(F.sum("amount").alias("total"),
                F.count("*").alias("orders"),
                F.round(F.avg("amount"), 1).alias("avg_amount"),
                F.countDistinct("customer_id").alias("customers"),
                F.sort_array(F.collect_set("product")).alias("products"))
           .orderBy(F.desc("total")))
summary.show(truncate=False)

# HAVING: filter after aggregating
summary.filter(F.col("total") > 50000).select("region", "total").show()

# Whole-table aggregate (no groupBy)
orders.agg(F.sum("qty").alias("units"), F.max("amount").alias("biggest")).show()

# Output:
# +------+--------+------+----------+---------+-----------------------+
# |region|total   |orders|avg_amount|customers|products               |
# +------+--------+------+----------+---------+-----------------------+
# |North |104500.0|3     |34833.3   |2        |[Laptop, Mouse, Tablet]|
# |West  |55000.0 |2     |27500.0   |2        |[Phone, Tablet]        |
# |South |54000.0 |2     |27000.0   |1        |[Laptop, Mouse]        |
# |East  |15000.0 |1     |15000.0   |1        |[Phone]                |
# +------+--------+------+----------+---------+-----------------------+
#
# +------+--------+
# |region|   total|
# +------+--------+
# | North|104500.0|
# |  West| 55000.0|
# | South| 54000.0|
# +------+--------+
#
# +-----+-------+
# |units|biggest|
# +-----+-------+
# |   15|55000.0|
# +-----+-------+

Key points

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic