Aggregates in SQL
Aggregate functions collapse many rows into a single value. Instead of getting a list of every row, you get one number: a total, an average, a count.
13 May 2024 · 2 min read

Aggregate functions collapse many rows into a single value. Instead of getting a list of every row, you get one number: a total, an average, a count.
These are the queries that answer business questions. "How many users do we have?" "What's the total revenue?" "Which continent has the highest GDP?"
Here's a walkthrough using a world database with country data.
Total population of the world
SELECT SUM(population)
FROM world
SUM adds up every value in the population column. One row back. One number.
List each continent once
SELECT DISTINCT continent
FROM world
DISTINCT removes duplicates. Without it, you'd get "Europe" repeated for every European country.
GDP of Africa
SELECT SUM(gdp)
FROM world
WHERE continent = 'Africa'
The WHERE clause filters rows before the aggregate runs. Only African countries contribute to this sum.
Count countries by continent
SELECT continent, COUNT(name)
FROM world
GROUP BY continent
GROUP BY splits the data into groups. COUNT runs separately on each group. You get one row per continent with the number of countries in each.
Continents with large populations
SELECT continent
FROM world
GROUP BY continent
HAVING SUM(population) > 500000000
HAVING filters after grouping. WHERE filters individual rows. HAVING filters groups. This returns only continents where the total population exceeds 500 million.
The pattern
Most aggregate queries follow the same shape:
WHEREfilters rowsGROUP BYcreates groups- Aggregate functions (
SUM,COUNT,AVG,MIN,MAX) compute per group HAVINGfilters groups
Get this pattern into muscle memory. It covers 90% of reporting queries you'll ever write.
Ehsan Gazar helps software engineers take LLM and agent systems from demo to production. He writes about building LLM systems that hold up in production: evals, tracing, RAG, agent architecture and cost control. He teaches the Senior to Staff AI Engineer cohort on Maven, where engineers learn to design and defend these systems.
Forward Deployed AI Engineering: From Customer Problem to Production Value
A live Maven cohort for engineers: 10 live 90-minute sessions taking one AI engagement from customer problem to production, ending with eight artefacts and a working slice in your own repo.
January cohort starts Tue 12 Jan 2027, Tue & Thu 6:30pm London. Enrolling now, 20 seats, $1,800.
View the live cohortKeep reading
- SQLZoo SELECT from WORLD: Solutions and Explanations
- SQLZoo SELECT Queries with Order BY
- The Art of SQL JOINs: Combining Data from Multiple Tables
- What is the difference between GROUP BY and HAVING clauses?
- Exploring SQL Subqueries: Advanced Queries for Data Analysis
- What is the difference between UNION and UNION ALL?