Summarising Data with GROUP BY · Lesson 17 of 64

SQL Aggregate Functions

What you will learn

  • What an aggregate function is
  • How COUNT, SUM, AVG, MIN and MAX work
  • How to combine several in one query
  • How WHERE filters the rows before they are summarised

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. Many rows in, one row out

So far every query returned one result row for each table row. An aggregate function reads many rows and returns one value that summarises them. The five you will use most:

Function Returns
COUNT(*) the number of rows
SUM(x) the total of the values of x
AVG(x) the average of x
MIN(x) the smallest value
MAX(x) the largest value

2. COUNT

SELECT COUNT(*) AS payments FROM payments;
payments
--------
    2295
(1 row)
SELECT COUNT(*) AS accounts FROM accounts;
accounts
--------
     450
(1 row)
SELECT COUNT(*) AS enrollments FROM enrollments;
enrollments
-----------
       1002
(1 row)

3. SUM, AVG, MIN and MAX

You can ask for several aggregates in one query. They are all calculated over the same rows:

SELECT COUNT(*) AS payments,
       ROUND(SUM(amount), 2) AS total,
       ROUND(AVG(amount), 2) AS average,
       MIN(amount) AS smallest,
       MAX(amount) AS largest
FROM payments;
payments      total  average  smallest  largest
--------  ---------  -------  --------  -------
    2295  233328.89   101.67       4.5   593.95
(1 row)
SELECT COUNT(*) AS accounts,
       SUM(balance_cents) AS total_cents,
       ROUND(AVG(balance_cents), 1) AS average_cents,
       MIN(balance_cents) AS smallest,
       MAX(balance_cents) AS largest
FROM accounts;
accounts  total_cents  average_cents  smallest  largest
--------  -----------  -------------  --------  -------
     450     62199130       138220.3      1300   502080
(1 row)
SELECT COUNT(*) AS assignments,
       SUM(max_points) AS total_points,
       ROUND(AVG(max_points), 2) AS average_points,
       MIN(max_points) AS smallest,
       MAX(max_points) AS largest
FROM assignments;
assignments  total_points  average_points  smallest  largest
-----------  ------------  --------------  --------  -------
        166          7755           46.72        10      100
(1 row)

The result has one row. We wrapped SUM and AVG in ROUND (lesson 1.6) because adding many decimals leaves tiny errors. MIN and MAX also work on text (alphabetical order) and on dates:

SELECT MIN(paid_on) AS first_payment, MAX(paid_on) AS last_payment FROM payments;
first_payment  last_payment
-------------  ------------
2024-01-05     2026-10-02
(1 row)
SELECT MIN(opened_on) AS oldest_account, MAX(opened_on) AS newest_account FROM accounts;
oldest_account  newest_account
--------------  --------------
2018-02-23      2026-07-26
(1 row)
SELECT MIN(birth_date) AS oldest_student, MAX(birth_date) AS youngest_student FROM students;
oldest_student  youngest_student
--------------  ----------------
2007-01-05      2013-12-31
(1 row)

4. WHERE comes first

WHERE chooses the rows, and the aggregates summarise only those rows:

Payments made by card:

SELECT COUNT(*) AS card_payments, ROUND(SUM(amount), 2) AS total FROM payments WHERE method = 'card';
card_payments      total
-------------  ---------
         1262  126798.77
(1 row)

Savings accounts that are open:

SELECT COUNT(*) AS accounts, SUM(balance_cents) AS total_cents FROM accounts WHERE account_type = 'savings' AND status = 'open';
accounts  total_cents
--------  -----------
     120     16220959
(1 row)

Courses with four or more credits:

SELECT COUNT(*) AS courses, SUM(credits) AS total_credits FROM courses WHERE credits >= 4;
courses  total_credits
-------  -------------
      7             28
(1 row)

The order is: pick the rows with WHERE, then summarise them. You cannot use an aggregate inside WHERE (for example WHERE price > AVG(price)); lesson 3.3 and chapter 7 show the tools for that.

5. An aggregate and a plain column

A query with an aggregate and no GROUP BY returns one row. Mixing a plain column with an aggregate is a mistake: which row's value should the column show? SQLite allows it and shows a value from one of the rows. Do not do it by accident. Lesson 3.2 shows the right way: GROUP BY.

In other databases. MySQL 8.4 rejects such a query by default (its documentation shows error 1055 for a non-aggregated column that is not in GROUP BY, because the ONLY_FULL_GROUP_BY mode is on by default). PostgreSQL's documentation says that in a grouped query columns not listed in GROUP BY cannot be referenced except in aggregate expressions, with an exception for columns that depend on a primary key. These statements come from the official documentation and were not run here.

SELECT MAX(amount) AS largest FROM payments;
largest
-------
 593.95
(1 row)
SELECT MAX(balance_cents) AS largest FROM accounts;
largest
-------
 502080
(1 row)
SELECT MAX(max_points) AS largest FROM assignments;
largest
-------
    100
(1 row)

To find which row holds the maximum, sort and limit instead (lesson 2.7): ORDER BY amount DESC LIMIT 1.

Worked example: a one-line summary of a table

A manager asks: "How big is the payments table, and what is a typical payment?"

Question Aggregate
how many? COUNT(*)
how much in total? SUM(amount)
what is typical? AVG(amount)
what is the range? MIN(amount) and MAX(amount)

One query answers all five, and ROUND makes the decimals readable. The table is made up.

Common mistakes

  • Mixing a plain column with an aggregate without GROUP BY.
  • Using an aggregate in WHERE. WHERE runs before the summary exists.
  • Forgetting that the result is one row.
  • Summing text. SUM is for numbers.
  • Not rounding SUM or AVG of decimals.

Key takeaways

  • An aggregate turns many rows into one value: COUNT, SUM, AVG, MIN, MAX.
  • Several aggregates can share one query.
  • WHERE selects the rows first; the aggregate summarises only those.
  • MIN and MAX also work on text and dates.
  • Do not mix a plain column with an aggregate; use GROUP BY.

Practice

1. What does SELECT COUNT(*) FROM customers; return?

Show answer

One number: how many rows the table has.

2. Write a query for the highest price in a products table.

Show answer

SELECT MAX(price) FROM products;

3. How many rows does a query with only aggregates and no GROUP BY return?

Show answer

Exactly one.

4. Why wrap AVG of a decimal column in ROUND?

Show answer

Averages of decimals often have many digits or tiny errors; rounding makes the result readable.

5. Why does WHERE price > AVG(price) give an error?

Show answer

WHERE is applied to each row before any aggregate has been calculated, so an aggregate cannot be used there.

6. How do you find the date of the most recent payment?

Show answer

SELECT MAX(paid_on) FROM payments; (dates in YYYY-MM-DD compare correctly).