Aggregate Functions

Updated · 7 min read
easyPostgreSQL 18sqlaggregatecountsumavgminmaxinterview

An aggregate function turns many rows into one value. How many payments have come in? What's the total? What's the largest single payment? Each answer summarizes a whole column into one number. SQL has five everyday aggregate functions: count, sum, avg, min and max. This lesson covers each one, how they treat NULL, a surprise with averages of whole numbers, and what they return when there are no rows at all.

In One Minute

  • count, sum, avg, min and max each turn a column into one value.
  • count(*) counts rows; count(column) counts the non-NULL values in a column.
  • sum, avg, min and max skip NULL; they don't treat it as zero.
  • In PostgreSQL, avg() of whole numbers gives a decimal; some databases give a whole number.
  • With no rows, count gives 0 and the others give NULL; coalesce(sum(...), 0) turns that into 0.

The Basics

SQL
SELECT aggregate_function(column), ...
FROM table_name
[WHERE condition];
FunctionReturnsWorks on
count(*)Number of rowsAny table
count(column)Number of non-NULL valuesAny column
sum(column)TotalNumbers
avg(column)Average (mean)Numbers
min(column)Smallest valueNumbers, text, dates
max(column)Largest valueNumbers, text, dates

All five at once, on every payment:

SQL▶ Try it
SELECT count(*) AS payments,
       sum(amount_usd) AS total,
       avg(amount_usd) AS average,
       min(amount_usd) AS smallest,
       max(amount_usd) AS largest
FROM payments;
Output
 payments |  total  |       average        | smallest | largest
----------+---------+----------------------+----------+---------
        7 | 2150.00 | 307.1428571428571429 |   200.00 |  550.00
(1 row)

Seven payment rows went in; one summary row came out. The average shows many decimal places because avg keeps the full precision; round(avg(amount_usd), 2) shows it as money:

SQL▶ Try it
SELECT round(avg(amount_usd), 2) AS average
FROM payments;
Output
 average
---------
  307.14
(1 row)
Seven payments in, one summary row out

Aggregates and WHERE

WHERE filters first, then the aggregate summarizes what's left. The total paid by card:

SQL▶ Try it
SELECT count(*) AS card_payments, sum(amount_usd) AS card_total
FROM payments
WHERE method = 'card';
Output
 card_payments | card_total
---------------+------------
             4 |    1475.00
(1 row)

Four card payments, totaling $1,475.00. Aggregates can't go inside WHERE itself, because WHERE decides row by row, before anything is summarized; WHERE sum(amount_usd) > 500 fails with aggregate functions are not allowed in WHERE. Filtering on a summary is what HAVING is for, two lessons from now.

The Smallest and Largest: Text and Dates Too

min and max work on anything that can be sorted. The first and last payment dates, and the first and last course titles in sort order:

SQL▶ Try it
SELECT min(paid_on) AS first_payment, max(paid_on) AS last_payment
FROM payments;
 
SELECT min(title) AS first_title, max(title) AS last_title
FROM courses;
Output
 first_payment | last_payment
---------------+--------------
 2025-08-28    | 2026-01-05
(1 row)
 
 first_title | last_title
-------------+------------
 Git Basics  | SQL Basics
(1 row)

For text, "smallest" means first in the collation's sort order, as in ORDER BY.

How Aggregates Treat NULL

sum, avg, min, max and count(column) skip NULL values. They summarize only the values that exist, which is usually what you want, but changes some answers. Only two courses have a prerequisite:

SQL▶ Try it
SELECT count(*) AS courses,
       count(prerequisite_id) AS with_prerequisite,
       avg(prerequisite_id) AS average_prerequisite
FROM courses;
Output
 courses | with_prerequisite | average_prerequisite
---------+-------------------+----------------------
       6 |                 2 |   1.5000000000000000
(1 row)

avg(prerequisite_id) is the average of the two values that exist, 1 and 2, giving 1.5. It doesn't divide by all six courses, and it doesn't count the missing ones as zero.

count(*) counts every row; the others use only the values that exist

AVG of Whole Numbers

In PostgreSQL, the average of an integer column is a decimal. The students' grades are 12, 10 and 7:

SQL▶ Try it
SELECT sum(grade) AS total, count(grade) AS students, avg(grade) AS average
FROM students;
Output
 total | students |      average
-------+----------+--------------------
    29 |        3 | 9.6666666666666667
(1 row)

29 divided by 3 is 9.666..., and PostgreSQL returns it as a decimal. That differs between databases: SQL Server returns the average of an integer column as an integer (9 here), so you'd write avg(grade * 1.0) there to keep the fraction (SQL Server only). MySQL and Oracle return a decimal. Tabs showing each database's version are coming to this course.

Aggregates with No Rows

When no rows match, count returns 0 and the other aggregates return NULL. Advitha has made no payments:

SQL▶ Try it
SELECT count(*) AS payments, sum(amount_usd) AS total, avg(amount_usd) AS average, max(amount_usd) AS largest
FROM payments
WHERE student_id = 102;
Output
 payments | total | average | largest
----------+-------+---------+---------
        0 |  NULL |    NULL |    NULL
(1 row)

There's still one result row. Zero payments is a known count, but the total, average and largest of nothing are unknown, so they're NULL.

When a report should show 0 instead, wrap the aggregate in coalesce, which replaces NULL with the value you give:

SQL▶ Try it
SELECT coalesce(sum(amount_usd), 0) AS total
FROM payments
WHERE student_id = 102;
Output
 total
-------
     0
(1 row)
No rows: count is 0, sum and avg are NULL; coalesce gives 0

You'll meet coalesce properly in NULL Functions.

Common Mistakes

Expecting sum to treat NULL as zero and still count it. avg divides by the number of non-NULL values, not by the number of rows.

Using count(column) when you mean count(*). count(method) is 6; count(*) is 7. Pick the one that answers your question.

Putting an aggregate in WHERE. It fails. Use HAVING.

Showing a raw average. avg returns many decimal places; round(avg(...), 2) is easier to read.

Assuming a total is 0 when nothing matched. It's NULL. Use coalesce(sum(...), 0).

Interview Corner

What is the difference between COUNT(*) and COUNT(column)?

count(*) counts every row. count(column) counts only the rows where that column isn't NULL. On payments, count(*) is 7 and count(method) is 6.

Does AVG include NULL values?

No. avg sums the non-NULL values and divides by how many there are. Rows with NULL are ignored entirely, not counted as zero.

What does SUM return when no rows match?

NULL, not 0. count returns 0. Use coalesce(sum(x), 0) when you need a zero.

Practice

Challenge: For the payments made in December 2025, show how many there were, their total, and their average rounded to cents. Use a half-open date range.

Show solution
SQL▶ Try it
SELECT count(*) AS payments,
       sum(amount_usd) AS total,
       round(avg(amount_usd), 2) AS average
FROM payments
WHERE paid_on >= '2025-12-01' AND paid_on < '2026-01-01';
Output
 payments |  total  | average
----------+---------+---------
        3 | 1025.00 |  341.67
(1 row)

Three payments, totaling $1,025.00: the same December total you saw in What Is a Database.

Quick check: Aggregate functions

3 questions
1On payments, count(*) is 7 and count(method) is 6. Why?
2Only courses 2 and 3 have prerequisites (1 and 2). What is avg(prerequisite_id) over all six courses?
3What does sum(amount_usd) return for a student with no payments?

Key Takeaways

You want toWrite
Count rowscount(*)
Count values that existcount(method)
Total, rounded averagesum(amount_usd), round(avg(amount_usd), 2)
Earliest and latestmin(paid_on), max(paid_on)
Zero instead of NULLcoalesce(sum(amount_usd), 0)

Was this tutorial helpful?

Lesson 24 of 115