Menu

Aggregate Functions and GROUP BY

Lesson 3: Aggregate Functions and GROUP BY

What are aggregate functions?

Aggregate functions summarise many rows into a single value.

Function

What it returns

Treats NULLs

COUNT(*)Number of rowsCounts all rows
COUNT(column)Number of non-NULL valuesExcludes NULLs
COUNT(DISTINCT column)Number of unique non-NULL valuesExcludes NULLs
SUM(column)TotalIgnores NULLs
AVG(column)MeanIgnores NULLs (not treated as zero)
MIN(column) / MAX(column)Smallest / largestIgnores NULLs

Example

SELECT region,
SUM(total_amount) AS revenue,
COUNT(*) AS order_count,
AVG(total_amount) AS avg_order_value
FROM orders
GROUP BY region
ORDER BY revenue DESC;

region

revenue

order_count

avg_order_value

South4,25,0003101,371
North3,80,0002951,288

How it works

  • GROUP BY creates one group per distinct value (here, per region).
  • Aggregate functions calculate a result for each group.
  • Every selected column that isn't aggregated generally must appear in GROUP BY (rules vary slightly by database).

Logical order in which SQL processes a query:

Order

Clause

1FROM / JOIN
2WHERE
3GROUP BY
4HAVING
5SELECT
6ORDER BY
7LIMIT

This explains why you usually can't use a SELECT alias inside WHERE: WHERE runs first.

HAVING versus WHERE

Clause

Filters

When it runs

Can use aggregates?

WHEREIndividual rowsBefore groupingNo
HAVINGGroupsAfter groupingYes
SELECT region, SUM(total_amount) AS revenue
FROM orders
WHERE order_date >= '2026-01-01' -- row filter
GROUP BY region
HAVING SUM(total_amount) > 10000; -- group filter

Common mistakes

  • Wrong unit of analysis: averaging line items gives a different result from averaging orders.
  • COUNT(column) vs COUNT(*)****: COUNT(column) excludes NULLs, while COUNT(*) counts all rows.
  • Counting duplicates: use COUNT(DISTINCT customer_id) for unique customers.
  • Filtering aggregates with WHERE: WHERE SUM(...) > 100 causes an error. Use HAVING.
  • Integer division: in some systems (PostgreSQL, SQL Server), 5 / 2 = 2. Multiply by 1.0 for decimals.

Try it: Calculate monthly revenue and order count. Then show only months with more than 100 orders.


Data Analytics Tutorial



Learn via Video Course

Data Analysis and Processing with Python using Pandas - Data Science Course Logo

Data Analysis and Processing with Python using Pandas - Data Science Course

5 hrs



Get in Touch For Details