SQL Aggregate Functions: COUNT, SUM, AVG, MIN, MAX
So far every query has returned rows from the table. Aggregate functions collapse many rows into a single value: how many books are there, how many copies are in stock, what is the average price? They are the foundation of every report and dashboard.
The five you will use daily
count(*)counts rows.sum(column)adds up the values.avg(column)computes the mean.min(column)andmax(column)find the smallest and largest values. They also work on text (alphabetical order) and on ISO dates stored as text.
Without a GROUP BY clause, which is the next chapter, an aggregate query treats the whole table, or whatever rows pass the WHERE filter, as one group and returns exactly one row.
Expected output
books | copies | avg_price | cheapest | newest 10 | 101 | 22.57 | 11.0 | 2024 genres 3
Rounding
avg(price) returns a floating-point number such as 22.568. Wrap it in round(value, 2) to get two decimals. Rounding belongs at the very end of a calculation; rounding each price first and then averaging can produce a slightly different answer.
COUNT variations
count(*)counts every row.count(column)counts rows where that column is notNULL.count(DISTINCT column)counts different non-NULLvalues. Our ten books fall into three genres.
Filtering before aggregating
WHERE runs before the aggregates, so SELECT avg(price) FROM books WHERE genre = 'Tech'; averages only Tech books. You cannot put an aggregate inside WHERE, as in WHERE price > avg(price), because the average does not exist yet at that stage. That needs a subquery, covered in a later chapter.
Mixing aggregates and plain columns
In standard SQL, a query that uses aggregates may only select plain columns that are also listed in GROUP BY. SQLite is lenient and lets you write SELECT title, max(price) FROM books, returning the title from the row with the maximum price. Other databases reject that query, so do not rely on it if your SQL needs to be portable.
Common mistakes
- Expecting
count(column)to count rows withNULLs. - Using an aggregate inside
WHERE. - Summing floating-point money and expecting exact cents; store cents as integers for exact totals.
Summary
count,sum,avg,minandmaxreduce many rows to one value.- Without
GROUP BY, the whole filtered table is one group. count(DISTINCT col)counts unique values;round()tidies decimals.WHEREfilters rows before aggregation.
Quiz: COUNT, SUM, AVG, MIN, MAX