Sub topic 1
Summarizing a table with aggregate functions
An aggregate function takes many rows and returns one value. This chapter covers the five standard aggregates (COUNT, SUM, AVG, MIN, MAX), what they do when no GROUP BY is present, and the errors that appear most often when you first use them. Later chapters build on this: NULL handling, COUNT variants and grouping each get their own treatment.
Prerequisites
This chapter assumes you can already:
- Write a basic
SELECT ... FROM ... WHERE ... ORDER BYquery. - Read a table as rows and columns, and tell numeric, text, date and boolean types apart.
- Recognize
NULLas a marker for a missing value, not as zero or an empty string.
You do not need joins or GROUP BY yet. The examples use an orders table:
| order_id | customer_id | status | amount | shipped_at |
|---|---|---|---|---|
| 1 | 10 | paid | 120.00 | 2026-01-03 |
| 2 | 10 | paid | 80.00 | NULL |
| 3 | 11 | refunded | 50.00 | 2026-01-05 |
| 4 | 12 | paid | NULL | NULL |
Here amount is NUMERIC(10,2), and shipped_at is a nullable DATE.
What an aggregate function does
A normal (scalar) function runs once per row: UPPER(name) gives one output per input row. An aggregate function runs over a set of rows and gives back one value for the whole set.
The five standard aggregates are:
| Function | Returns | Works on |
|---|---|---|
| `COUNT(x)` | How many non-NULL values | Any type |
| `SUM(x)` | Total of non-NULL values | Numeric types |
| `AVG(x)` | Mean of non-NULL values | Numeric types |
| `MIN(x)` | Smallest non-NULL value | Numbers, text, dates |
| `MAX(x)` | Largest non-NULL value | Numbers, text, dates |
COUNT(*) is a special form. It counts rows, not values, so it never skips anything.
One group for the whole table
If a query uses aggregates and has no GROUP BY, the database treats the entire table (after any WHERE filter) as a single group. The result is exactly one row.
SELECT COUNT(*) AS order_count,
SUM(amount) AS total_amount,
AVG(amount) AS avg_amount,
MIN(amount) AS smallest,
MAX(amount) AS largest
FROM orders;With the sample data above, the result is:
| order_count | total_amount | avg_amount | smallest | largest |
|---|---|---|---|---|
| 4 | 250.00 | 83.33 | 50.00 | 120.00 |
Notice that order_count is 4, but AVG(amount) is 83.33, which is 250 divided by 3, not by 4. Order 4 has a NULL amount, and every aggregate except COUNT(*) ignores NULL inputs. Skipping NULLs is the most important rule in this chapter, and the next chapter develops it fully.
Each function in detail
COUNT
COUNT(*) returns the number of rows in the group. COUNT(column) returns the number of rows where that column is not NULL. On an empty set, both return 0, never NULL.
SUM
SUM adds the non-NULL values. Two details matter:
- On an empty set, or when every value is
NULL,SUMreturnsNULL, not0. If you need a zero for reports, wrap it:COALESCE(SUM(amount), 0). - The result type can be wider than the input type. In PostgreSQL,
SUMof anintegercolumn returnsbigint, andSUMof abigintreturnsnumeric. This avoids overflow, but it can surprise application code that expects a specific type.
AVG
AVG divides the sum of non-NULL values by the count of non-NULL values. It is not the sum divided by COUNT(*). If you want NULLs treated as zero, say so explicitly:
SELECT AVG(amount) AS avg_ignoring_nulls,
AVG(COALESCE(amount, 0)) AS avg_nulls_as_zero
FROM orders;On the sample data this gives 83.33 and 62.50. Which one is correct depends on what a missing amount means in your business. A NULL amount might mean "not yet priced" (exclude it) or "free" (use zero). The database cannot decide for you.
Integer division is a common trap. In some databases, AVG of an integer column returns an integer or a truncated value. PostgreSQL returns numeric, and MySQL returns a decimal, but SQL Server returns an int for AVG over an int column. If you compute a mean by hand, as SUM(x) / COUNT(x) over integer columns, you can get truncation in PostgreSQL and SQL Server. Cast one side first: SUM(x) * 1.0 / COUNT(x).
MIN and MAX
MIN and MAX compare values using the type's ordering, so they work on numbers, dates and text. For text, the result depends on the collation (the rule set for sorting strings), so MAX(name) can differ between a case-sensitive and a case-insensitive database.
SELECT MIN(shipped_at) AS first_shipment,
MAX(shipped_at) AS latest_shipment
FROM orders;Both ignore NULL. On the sample data the result is 2026-01-03 and 2026-01-05.
Filtering before aggregating
A WHERE clause runs before aggregation, so it decides which rows the aggregates see.
SELECT COUNT(*) AS paid_orders,
SUM(amount) AS paid_total
FROM orders
WHERE status = 'paid';Result: paid_orders = 3 and paid_total = 200.00. Order 4 is counted because it is paid, even though its amount is NULL. This is a good example of why COUNT(*) and SUM(amount) can tell different stories about the same rows.
If WHERE matches no rows, you still get exactly one output row:
SELECT COUNT(*) AS n,
SUM(amount) AS total
FROM orders
WHERE status = 'cancelled';Result: n = 0 and total = NULL. An ungrouped aggregate query never returns zero rows. This matters when application code assumes "no matches means no row".
DISTINCT inside an aggregate
You can put DISTINCT inside an aggregate call so that duplicate values are counted or summed once:
SELECT COUNT(customer_id) AS customer_refs,
COUNT(DISTINCT customer_id) AS distinct_customers,
SUM(DISTINCT amount) AS sum_of_distinct_amounts
FROM orders;COUNT(DISTINCT customer_id) is useful and common (here it returns 3 against 4 plain references). SUM(DISTINCT amount) is rarely what you want: if two different orders both cost 80.00, one of them silently disappears from the total. Treat it as a warning sign unless you can explain why it is correct.
The mixing rule
An aggregate query without GROUP BY cannot also select a plain column. This fails:
SELECT customer_id, COUNT(*)
FROM orders;PostgreSQL reports that customer_id must appear in the GROUP BY clause or be used in an aggregate function. The reasoning is simple: the query returns one row for the whole table, and the table has several customer_id values. The database has no way to choose which one to show.
MySQL used to accept this query by returning an arbitrary value, but its default ONLY_FULL_GROUP_BY mode (on since MySQL 5.7.5) now rejects it. SQLite still accepts some forms of it. Do not rely on lenient behavior, because it returns values that look plausible and are not meaningful.
The fix is either to remove the plain column or to introduce GROUP BY, which is the subject of a later chapter.
Aggregates cannot appear in WHERE
Because WHERE runs before aggregation, this is an error:
SELECT order_id
FROM orders
WHERE amount > AVG(amount);The database has not computed AVG(amount) at the point where WHERE is evaluated. To compare each row with the overall average, use a scalar subquery, which computes the average as a separate step:
SELECT order_id, amount
FROM orders
WHERE amount > (SELECT AVG(amount) FROM orders);On the sample data, this returns order 1 (120.00), since the average is 83.33. Rows with a NULL amount are dropped, because comparing NULL to anything gives unknown, and WHERE keeps only rows where the condition is true.
Nesting and combining aggregates
You can compute with aggregate results, and you can use aggregates in the same select list as one another:
SELECT MAX(amount) - MIN(amount) AS spread,
SUM(amount) / COUNT(*) AS naive_mean
FROM orders;spread is 70.00. naive_mean is 62.50 because COUNT(*) includes the NULL row, which is a good illustration of why AVG(amount) and SUM(amount) / COUNT(*) are different quantities.
Most databases do not allow an aggregate directly inside another aggregate, so SUM(COUNT(*)) fails in a query without GROUP BY. When you need a second level of summarization, put the first level in a subquery or a common table expression.
Common errors at a glance
| Symptom | Likely cause | Fix |
|---|---|---|
| Error about column "must appear in GROUP BY" | Plain column selected next to an aggregate | Remove the column or add `GROUP BY` |
| Error "aggregate functions are not allowed in WHERE" | Aggregate used in row filter | Use a subquery, or `HAVING` with `GROUP BY` |
| Average looks too high | `NULL` rows excluded from `AVG` | Decide whether to use `COALESCE` |
| Total is `NULL` instead of 0 | `SUM` over empty or all-NULL set | `COALESCE(SUM(x), 0)` |
| Count does not match expectations | `COUNT(column)` skips NULLs | Use `COUNT(*)` if you want all rows |
| Truncated average | Integer division | Cast to `numeric` or multiply by `1.0` |
Summary
- An aggregate function reduces a set of rows to one value.
- Without
GROUP BY, the whole filtered table is one group, and the query always returns exactly one row. COUNT(*)counts rows. Every other aggregate ignoresNULLinputs.SUMandAVGover nothing returnNULL;COUNTreturns0.WHEREfilters rows before aggregation, so it cannot contain aggregates.- A plain column cannot sit next to an aggregate unless it is grouped.
Exercise
Using the sample orders table (amounts 120.00, 80.00, 50.00 and NULL), what do COUNT(*), COUNT(amount), SUM(amount) and AVG(amount) return, and what does SUM(amount) / COUNT(*) return?
Show answer
COUNT(*) is 4 because it counts every row. COUNT(amount) is 3 because it skips the NULL. SUM(amount) is 250.00. AVG(amount) is 250.00 / 3 = 83.33, since the NULL row is excluded from both the sum and the divisor. SUM(amount) / COUNT(*) is 250.00 / 4 = 62.50, because COUNT(*) includes the NULL row.
Exercise
Write a query that returns the number of orders with status 'refunded' and their total amount, so that the total shows 0 instead of NULL when there are no refunded orders. Then say how many rows the query returns when no order is refunded.
Show answer
SELECT COUNT(*) AS refundedorders, COALESCE(SUM(amount), 0) AS refundedtotal FROM orders WHERE status = 'refunded'; An aggregate query without GROUP BY always returns exactly one row, so it returns one row with refundedorders = 0 and refundedtotal = 0.
Exercise
Why does SELECT order_id FROM orders WHERE amount > AVG(amount); fail, and how would you rewrite it to list orders above the average amount?
Show answer
WHERE is evaluated before aggregation, so the average does not exist yet and aggregates are not allowed there. Rewrite it with a scalar subquery: SELECT order_id, amount FROM orders WHERE amount > (SELECT AVG(amount) FROM orders);