๐Ÿ“Š GROUP BY & Aggregations

Aggregation turns many rows into a summary: total sales per day, headcount per department, average salary per city. In this tutorial you will learn the aggregate functions, GROUP BY, HAVING, and a few Spark SQL extras such as FILTER, max_by and collect_list that make common questions much easier to answer.


1. Sample Data

All examples use the employees view from the Introduction to Spark SQL:

CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
  (1, 'Asha',  'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
  (2, 'Ben',   'Engineering', 82000, DATE'2020-07-01', 1,    'Pune'),
  (3, 'Chen',  'Sales',       60000, DATE'2021-01-10', 1,    'Mumbai'),
  (4, 'Divya', 'Sales',       65000, DATE'2018-11-23', 3,    'Mumbai'),
  (5, 'Elena', 'Marketing',   58000, DATE'2022-05-30', 1,    NULL),
  (6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2,    'Bengaluru'),
  (7, 'Grace', NULL,          45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)

2. Aggregating the Whole Table

An aggregate function reads many rows and returns one value. Without GROUP BY, the whole table is one group, so you get one row back:

SELECT COUNT(*)    AS employees,
       SUM(salary) AS total_salary,
       AVG(salary) AS avg_salary,
       MIN(salary) AS min_salary,
       MAX(salary) AS max_salary
FROM employees
+---------+------------+-----------------+----------+----------+
|employees|total_salary|avg_salary       |min_salary|max_salary|
+---------+------------+-----------------+----------+----------+
|7        |487000      |69571.42857142857|45000     |95000     |
+---------+------------+-----------------+----------+----------+
FunctionReturns
COUNT(*)Number of rows
SUM(col)Total of the values
AVG(col)Average of the values
MIN(col) / MAX(col)Smallest / largest value (works on numbers, text and dates)

3. COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column)

These three look alike but count different things:

SELECT COUNT(*)             AS all_rows,
       COUNT(dept)          AS rows_with_dept,
       COUNT(DISTINCT dept) AS unique_depts,
       COUNT(city)          AS rows_with_city,
       COUNT(DISTINCT city) AS unique_cities
FROM employees
+--------+--------------+------------+--------------+-------------+
|all_rows|rows_with_dept|unique_depts|rows_with_city|unique_cities|
+--------+--------------+------------+--------------+-------------+
|7       |6             |3           |6             |4            |
+--------+--------------+------------+--------------+-------------+
  • COUNT(*) counts rows: 7.
  • COUNT(dept) counts rows where dept is not NULL: 6, because Grace has no department.
  • COUNT(DISTINCT dept) counts unique non-NULL values: Engineering, Sales and Marketing.

This is a general rule: aggregate functions skip NULL values. Only COUNT(*) counts every row.

Interview tip: "What is the difference between COUNT(*) and COUNT(col)?" is asked constantly. COUNT(col) ignores NULL values, so the two differ whenever the column has missing data.


4. Grouping with GROUP BY

GROUP BY splits the rows into groups that share a value, then runs the aggregates once per group:

SELECT dept,
       COUNT(*)    AS headcount,
       SUM(salary) AS total_salary,
       MAX(salary) AS top_salary
FROM employees
GROUP BY dept
ORDER BY dept
+-----------+---------+------------+----------+
|dept       |headcount|total_salary|top_salary|
+-----------+---------+------------+----------+
|NULL       |1        |45000       |45000     |
|Engineering|3        |259000      |95000     |
|Marketing  |1        |58000       |58000     |
|Sales      |2        |125000      |65000     |
+-----------+---------+------------+----------+

Each department becomes one row. Grace's NULL department forms its own group: for grouping, all NULL values count as the same key.


5. Grouping by Several Columns

List more columns to make the groups finer. Each unique combination becomes a group:

SELECT dept, city, COUNT(*) AS headcount
FROM employees
WHERE dept IS NOT NULL
GROUP BY dept, city
ORDER BY dept, city
+-----------+---------+---------+
|dept       |city     |headcount|
+-----------+---------+---------+
|Engineering|Bengaluru|2        |
|Engineering|Pune     |1        |
|Marketing  |NULL     |1        |
|Sales      |Mumbai   |2        |
+-----------+---------+---------+

Engineering is now split into Bengaluru (Asha and Farid) and Pune (Ben).


6. The "Not in GROUP BY" Error

Every column in SELECT must either be in GROUP BY or be inside an aggregate function. This query asks for name, but a department has several names, so Spark does not know which one to show:

SELECT dept, name
FROM employees
GROUP BY dept
[MISSING_AGGREGATION] The non-aggregating expression "name" is based on columns which are not participating in the GROUP BY clause.

You have three options, depending on what you meant:

You wantWrite
One row per department and nameAdd it to the grouping: GROUP BY dept, name
A specific name per department (the first alphabetically, for example)Aggregate it: MIN(name)
Any name, you do not care whichany_value(name)
SELECT dept, MIN(name) AS first_name_alphabetically
FROM employees
GROUP BY dept
ORDER BY dept
+-----------+-------------------------+
|dept       |first_name_alphabetically|
+-----------+-------------------------+
|NULL       |Grace                    |
|Engineering|Asha                     |
|Marketing  |Elena                    |
|Sales      |Chen                     |
+-----------+-------------------------+

7. Filtering Groups with HAVING

WHERE filters rows before grouping. HAVING filters groups after aggregation, so it can use aggregate results:

SELECT dept, COUNT(*) AS headcount, AVG(salary) AS avg_salary
FROM employees
WHERE salary >= 50000
GROUP BY dept
HAVING COUNT(*) >= 2
ORDER BY dept
+-----------+---------+-----------------+
|dept       |headcount|avg_salary       |
+-----------+---------+-----------------+
|Engineering|3        |86333.33333333333|
|Sales      |2        |62500.0          |
+-----------+---------+-----------------+

Step by step:

  1. WHERE salary >= 50000 removes Grace (45,000) before any grouping.
  2. GROUP BY dept forms Engineering (3 rows), Sales (2) and Marketing (1).
  3. HAVING COUNT(*) >= 2 removes Marketing, which has only one employee.
WHEREHAVING
RunsBefore GROUP BYAfter GROUP BY
FiltersIndividual rowsWhole groups
Can use aggregates like COUNT(*)NoYes

Common mistake: Putting a row condition in HAVING, such as HAVING salary >= 50000. Filter rows in WHERE: it runs earlier, so Spark groups fewer rows.


8. Conditional Aggregates: FILTER and count_if

Often you want several counts with different conditions in one pass. Add FILTER (WHERE ...) after an aggregate to make it look at only some rows:

SELECT dept,
       COUNT(*)                                        AS headcount,
       COUNT(*) FILTER (WHERE salary > 70000)          AS high_earners,
       SUM(salary) FILTER (WHERE hire_date >= DATE'2021-01-01') AS salary_of_recent_hires
FROM employees
WHERE dept IS NOT NULL
GROUP BY dept
ORDER BY dept
+-----------+---------+------------+----------------------+
|dept       |headcount|high_earners|salary_of_recent_hires|
+-----------+---------+------------+----------------------+
|Engineering|3        |3           |82000                 |
|Marketing  |1        |0           |58000                 |
|Sales      |2        |0           |60000                 |
+-----------+---------+------------+----------------------+

Marketing and Sales have no high earners, so their counts are 0. Each department has exactly one hire since 2021: Farid (82,000) in Engineering, Elena (58,000) in Marketing and Chen (60,000) in Sales.

For counting, count_if(condition) is a shorter form:

SELECT count_if(salary > 70000)    AS high_earners,
       count_if(city = 'Bengaluru') AS in_bengaluru
FROM employees
+------------+------------+
|high_earners|in_bengaluru|
+------------+------------+
|3           |2           |
+------------+------------+

You can get the same results with SUM(CASE WHEN ... THEN 1 ELSE 0 END), which works in every database. The CASE WHEN tutorial shows that pattern.


9. Who Has the Max? max_by and min_by

"Who is the highest paid in each department?" is a classic question. MAX(salary) gives the salary but not the person. max_by(x, y) returns the value of x from the row with the largest y:

SELECT dept,
       MAX(salary)             AS top_salary,
       max_by(name, salary)    AS top_earner,
       max_by(name, hire_date) AS newest_hire
FROM employees
WHERE dept IS NOT NULL
GROUP BY dept
ORDER BY dept
+-----------+----------+----------+-----------+
|dept       |top_salary|top_earner|newest_hire|
+-----------+----------+----------+-----------+
|Engineering|95000     |Asha      |Farid      |
|Marketing  |58000     |Elena     |Elena      |
|Sales      |65000     |Divya     |Chen       |
+-----------+----------+----------+-----------+

top_salary only gives the number, while top_earner names the person. newest_hire uses the same idea with dates: Farid, Elena and Chen are the most recent hires in their departments.

If two rows tie for the largest y, max_by returns one of them, and which one is not guaranteed. Ben and Farid both earn 82,000, so min_by(name, salary) for Engineering could return either. When ties matter, use a window function such as ROW_NUMBER() with a tiebreaker, covered in Window Functions.


10. Collecting Values into a List

collect_list gathers the values of a group into an array; collect_set does the same but removes duplicates. Both skip NULL values.

SELECT dept,
       array_sort(collect_list(name)) AS names,
       array_sort(collect_list(city)) AS cities,
       array_sort(collect_set(city))  AS unique_cities
FROM employees
GROUP BY dept
ORDER BY dept
+-----------+------------------+----------------------------+-----------------+
|dept       |names             |cities                      |unique_cities    |
+-----------+------------------+----------------------------+-----------------+
|NULL       |[Grace]           |[Delhi]                     |[Delhi]          |
|Engineering|[Asha, Ben, Farid]|[Bengaluru, Bengaluru, Pune]|[Bengaluru, Pune]|
|Marketing  |[Elena]           |[]                          |[]               |
|Sales      |[Chen, Divya]     |[Mumbai, Mumbai]            |[Mumbai]         |
+-----------+------------------+----------------------------+-----------------+

Notice Marketing: Elena's city is NULL, so her cities array is empty.

Common mistake: Expecting collect_list to keep a particular order. Spark collects values from many partitions in parallel, so the order can change between runs. Wrap it in array_sort() when you need a stable result.


11. Types of Aggregate Results

Two details about the types Spark returns:

SELECT typeof(SUM(salary)) AS sum_type,
       typeof(AVG(salary)) AS avg_type,
       AVG(salary)         AS avg_salary,
       ROUND(AVG(salary), 2) AS avg_rounded
FROM employees
+--------+--------+-----------------+-----------+
|sum_type|avg_type|avg_salary       |avg_rounded|
+--------+--------+-----------------+-----------+
|bigint  |double  |69571.42857142857|69571.43   |
+--------+--------+-----------------+-----------+
  • SUM of an int column returns a bigint, which leaves far more room before a large total overflows.
  • AVG always returns a double, even for whole numbers. Use ROUND() for display.

And what happens when no rows match?

SELECT COUNT(*) AS num_rows, SUM(salary) AS total, MAX(salary) AS top
FROM employees
WHERE salary > 1000000
+--------+-----+----+
|num_rows|total|top |
+--------+-----+----+
|0       |NULL |NULL|
+--------+-----+----+

COUNT returns 0, but SUM, AVG, MIN and MAX return NULL: there is nothing to add up. Use coalesce(SUM(salary), 0) if you need a zero.


12. Shortcuts: GROUP BY ALL and GROUP BY Position

Listing every non-aggregated column twice gets tedious. Spark 3.5 supports GROUP BY ALL, which groups by every column in SELECT that is not an aggregate:

SELECT dept, city, COUNT(*) AS headcount
FROM employees
GROUP BY ALL
ORDER BY dept, city
+-----------+---------+---------+
|dept       |city     |headcount|
+-----------+---------+---------+
|NULL       |Delhi    |1        |
|Engineering|Bengaluru|2        |
|Engineering|Pune     |1        |
|Marketing  |NULL     |1        |
|Sales      |Mumbai   |2        |
+-----------+---------+---------+

You can also group by position (GROUP BY 1, 2), the same way ORDER BY 1 works. Both are handy for exploration. In shared code, explicit column names are easier to review.


13. Try It in the Online Compiler

Copy this into the PySpark Online Compiler:

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Spark SQL Group By").getOrCreate()

spark.sql("""
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
  (1, 'Asha',  'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
  (2, 'Ben',   'Engineering', 82000, DATE'2020-07-01', 1,    'Pune'),
  (3, 'Chen',  'Sales',       60000, DATE'2021-01-10', 1,    'Mumbai'),
  (4, 'Divya', 'Sales',       65000, DATE'2018-11-23', 3,    'Mumbai'),
  (5, 'Elena', 'Marketing',   58000, DATE'2022-05-30', 1,    NULL),
  (6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2,    'Bengaluru'),
  (7, 'Grace', NULL,          45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
""")

# Three kinds of COUNT
spark.sql("""
SELECT COUNT(*), COUNT(dept), COUNT(DISTINCT dept) FROM employees
""").show(truncate=False)

# Departments with at least 2 employees earning 50,000+
spark.sql("""
SELECT dept, COUNT(*) AS headcount, ROUND(AVG(salary), 2) AS avg_salary
FROM employees
WHERE salary >= 50000
GROUP BY dept
HAVING COUNT(*) >= 2
ORDER BY dept
""").show(truncate=False)

# Top earner and team members per department
spark.sql("""
SELECT dept, max_by(name, salary) AS top_earner, array_sort(collect_list(name)) AS team
FROM employees
WHERE dept IS NOT NULL
GROUP BY dept
ORDER BY dept
""").show(truncate=False)

Summary

  • Aggregates (COUNT, SUM, AVG, MIN, MAX) turn many rows into one value per group.
  • COUNT(*) counts rows; COUNT(col) skips NULL; COUNT(DISTINCT col) counts unique non-NULL values.
  • Every SELECT column must be grouped or aggregated, or you get MISSING_AGGREGATION.
  • WHERE filters rows before grouping; HAVING filters groups after.
  • FILTER (WHERE ...) and count_if compute conditional aggregates in one pass.
  • max_by / min_by return a value from the row with the max or min of another column.
  • collect_list / collect_set build arrays; wrap them in array_sort for a stable order.
  • AVG returns a double; SUM over no rows returns NULL, while COUNT returns 0.

Next, you will learn how to add if/else logic to your queries with CASE WHEN.