COUNT, SUM, AVG: Turning Rows into Numbers
A quick look ahead.
Some examples in this chapter may combine two tables with a JOIN. That's a Chapter 4 topic, and we'll cover it in detail there.
For now, when you see something like:
orders o
JOIN order_items oi ON oi.order_id = o.id
just read it as:
order rows were matched with order-item rows using a shared key.
Table joins aren't our focus yet. What matters here is : how SQL calculates a summary from a set of rows.
Chapter 3 — “The Store's Pulse”
The “Analyst” clearance appears on your badge as a warm amber stripe.
K.'s encrypted block still hasn't opened, but you know its heading by heart:
Raw rows — noise.
Meaning appears, when you know how to add them up.
QUERY dims the extra holopanels, leaving just one: empty, with a single pulsing dot in the center.
QUERY: You've been reading the archive row by row. Enough. Today, we'll listen to its heartbeat.

Up to this point, you've mostly been retrieving rows.
For example:
SELECT id, user_id, status, total_amount
FROM orders
WHERE status = 'paid';
This query shows paid orders one by one:
| id | user_id | status | total_amount |
|---|---|---|---|
| 1 | 18 | paid | 59.80 |
| 2 | 10 | paid | 197.50 |
| 4 | 26 | paid | 155.30 |
| 5 | 8 | paid | 267.10 |
| … | … | … | … |
And so on for all 86 paid orders. That's useful when you need to inspect the individual rows.
But business questions often ask for something different:
How many paid orders were there?
What was the total revenue?
What was the average order amount?
What were the minimum and maximum order amounts?
How many distinct customers placed an order?
You don't need a long list of rows to answer these questions. You need a summary.
SQL provides functions for this.
An aggregate function takes a set of rows and reduces it to a single summary value.
For example:
SELECT COUNT(*) AS orders_count
FROM orders;
This query doesn't show each order separately. It returns one number: the number of rows in the orders table.
Aggregate functions: many rows → one value
Aggregates turn a stream of rows into a metric you can say out loud.
Instead of:
order 1
order 2
order 4
order 5
You get:
total 4 orders
Instead of:
59.80
197.50
155.30
267.10
You get:
total amount 679.70
average order amount 169.93
minimum order amount 59.80
maximum order amount 267.10
The five main functions are:
| Function | What it calculates | Example question |
|---|---|---|
COUNT(*) | number of rows | How many orders are there? |
SUM(x) | sum of values | What's the revenue? |
AVG(x) | average value | What's the average order amount? |
MIN(x) | minimum value | What's the smallest order amount? |
MAX(x) | maximum value | What's the largest order amount? |
For example:
SELECT
COUNT(*) AS orders_count,
SUM(total_amount) AS revenue,
AVG(total_amount) AS avg_order_amount,
MIN(total_amount) AS min_order_amount,
MAX(total_amount) AS max_order_amount
FROM orders;
If a query has no GROUP BY, the aggregates calculate a result across the entire set of rows that reaches them.
The result is one row:
| orders_count | revenue | avg_order_amount | min_order_amount | max_order_amount |
|---|---|---|---|---|
| 120 | 18557.90 | 154.6491666666666667 | 8.90 | 421.10 |
COUNT: how many rows
COUNT answers the question “how many?”.
Its most common form is:
COUNT(*)
It counts rows.
For example:
SELECT COUNT(*) AS orders_count
FROM orders;
Result:
| orders_count |
|---|
| 120 |
The asterisk in COUNT(*) doesn't mean “select all columns.” Here it means:
count the rows themselves.
COUNT(*) doesn't care what values the columns contain. It only checks whether a row exists.
Use COUNT(*) when the question sounds like this:
How many orders are there in total?
How many products are there in total?
How many users are there in total?
How many rows remain after filtering?
For example, to count paid orders:
SELECT COUNT(*) AS paid_orders_count
FROM orders
WHERE status = 'paid';
Here, WHERE first keeps only the paid orders. Then COUNT(*) counts the remaining rows.
orders where status = 'refunded'. Your result should contain one number.SUM, AVG, MIN, and MAX
SUM calculates a total.
SELECT SUM(total_amount) AS revenue
FROM orders
WHERE status = 'paid';
This gives you the revenue from paid orders.
AVG calculates an average value.
SELECT AVG(total_amount) AS avg_order_amount
FROM orders
WHERE status = 'paid';
This gives you the average order amount for paid orders.
MIN finds the minimum value.
SELECT MIN(total_amount) AS min_order_amount
FROM orders
WHERE status = 'paid';
MAX finds the maximum value.
SELECT MAX(total_amount) AS max_order_amount
FROM orders
WHERE status = 'paid';
You can use all of these functions together:
SELECT
COUNT(*) AS paid_orders_count,
SUM(total_amount) AS revenue,
AVG(total_amount) AS avg_order_amount,
MIN(total_amount) AS min_order_amount,
MAX(total_amount) AS max_order_amount
FROM orders
WHERE status = 'paid';
This single query returns a summary of the paid orders.
WHERE filters rows first, then the aggregate calculates
The order of operations matters here.
In this query:
SELECT
COUNT(*) AS paid_orders_count,
SUM(total_amount) AS revenue
FROM orders
WHERE status = 'paid';
the filter runs first:
WHERE status = 'paid'
It keeps only paid orders.
Only then do the calculate a result from the remaining rows:
COUNT(*)
SUM(total_amount)
The query doesn't count every order and then somehow mark the paid ones afterward. It removes the rows you don't need first, then calculates the result.
You can use this pattern with any condition.
Revenue from paid orders only:
WHERE status = 'paid'
Number of canceled orders:
WHERE status = 'cancelled'
Average order amount for a specific period:
WHERE created_at >= '2024-01-01'
AND created_at < '2024-02-01'
First, SQL forms the set of rows. Then the aggregate turns that set into a number.
QUERY: Before you listen for a pulse, choose whose heart you're listening to. All orders, paid orders, and canceled orders each sound different.
status = 'cancelled') one by one. Replace the list with a single summary row for total_amount: the total, the average rounded to 2 decimal places, the smallest order, and the largest order — in exactly that order.COUNT(*) and COUNT(DISTINCT col) answer different questions.
COUNT(*) counts rows.
COUNT(DISTINCT user_id) counts how many distinct customers appear in those rows.
If there are more orders than customers, the archive isn't malfunctioning: one customer may have placed several orders.
COUNT(*), COUNT(col), COUNT(DISTINCT col)
COUNT has several forms, and each one answers a different question.
Consider a small example.
Suppose you have a visits table:
| id | promo_code |
|---|---|
| 1 | SALE |
| 2 | SALE |
| 3 | |
| 4 | VIP |
| 5 | NULL |
This query:
SELECT
COUNT(*) AS rows_count,
COUNT(promo_code) AS with_promo_code,
COUNT(DISTINCT promo_code) AS different_promo_codes
FROM visits;
returns:
| rows_count | with_promo_code | different_promo_codes |
|---|---|---|
| 5 | 3 | 2 |
Why?
COUNT(*) counts every row.
The table has 5 rows, so the result is 5.
COUNT(promo_code) counts rows where promo_code has a value.
It doesn't count NULL. Three rows have a promo code:
SALE
SALE
VIP
So the result is 3.
COUNT(DISTINCT promo_code) counts distinct filled values.
Among the filled values:
SALE
SALE
VIP
there are only two distinct values:
SALE
VIP
So the result is 2.
In short:
COUNT(*) → number of rows
COUNT(promo_code) → number of rows with a promo code
COUNT(DISTINCT promo_code) → number of distinct filled promo codes
These are three different questions about the data, so the answers can differ.
events table, each row stores one user action. For events where event_type = 'cart', return two numbers: the total number of such events and the number of distinct users (user_id) who performed them.Aggregates and NULL
The general rule is:
functions usually ignore NULL.
For example, suppose you have these values:
| total_amount |
|---|
| 1000 |
| 2000 |
SUM(total_amount) adds only the non-null values:
10.00 + 20.00 = 30.00
AVG(total_amount) also uses only the non-null values:
(10.00 + 20.00) / 2 = 15.00
It does not calculate this:
(10.00 + 20.00 + NULL) / 3
MIN and MAX also find the minimum and maximum among non-null values.
The important exception is COUNT(*).
COUNT(*) counts rows rather than values in a particular column, so NULL values inside columns don't affect it.
Compare:
SELECT
COUNT(*) AS rows_count,
COUNT(total_amount) AS filled_amounts,
SUM(total_amount) AS total_sum,
AVG(total_amount) AS avg_amount
FROM orders;
COUNT(*) answers the question:
how many rows
COUNT(total_amount) answers the question:
how many rows have filled total_amount
Those are different questions.
When no rows remain after WHERE
Sometimes a filter doesn't match any rows.
For example:
SELECT
COUNT(*) AS orders_count,
SUM(total_amount) AS revenue,
AVG(total_amount) AS avg_order_amount,
MIN(total_amount) AS min_order_amount,
MAX(total_amount) AS max_order_amount
FROM orders
WHERE status = 'status_that_does_not_exist';
If there are no such orders, the result still contains one row because an without GROUP BY returns one summary for the selected set.
But the values differ:
| orders_count | revenue | avg_order_amount | min_order_amount | max_order_amount |
|---|---|---|---|---|
| 0 | NULL | NULL | NULL |
COUNT(*) returns 0 because there are no rows.
SUM, AVG, MIN, and MAX return NULL because there is nothing to add, average, or compare.
If a report should show zero revenue instead of NULL, you can use COALESCE:
SELECT
COUNT(*) AS orders_count,
COALESCE(SUM(total_amount), 0.00) AS revenue
FROM orders
WHERE status = 'status_that_does_not_exist';
This doesn't change the data in the table. It simply shows 0.00 instead of an empty summary value in the query result.
COUNT(*) and COUNT(1)
Sometimes you'll see this in someone else's query:
COUNT(1)
For example:
SELECT COUNT(1)
FROM orders;
In PostgreSQL, for ordinary row counting, this means the same thing as:
SELECT COUNT(*)
FROM orders;
Why?
Because 1 is an expression that is never NULL. It evaluates to 1 for every row, so COUNT(1) counts every row.
For readability, though, it's better to write:
COUNT(*)
This makes it immediately clear that you're counting rows.
The claim that COUNT(1) is always faster than COUNT(*) isn't a useful rule for PostgreSQL. At this stage, remember the simpler rule:
if you need to count rows, use
COUNT(*).
Why a regular column next to an aggregate causes an error
Look at this query:
SELECT status, COUNT(*)
FROM orders;
It may look as though it should show a status and the number of orders.
But without GROUP BY, this query causes an error.
Why?
Without GROUP BY, COUNT(*) reduces all selected rows to one summary row.
For example:
| count |
|---|
| 120 |
But status is a regular column. Different orders can have different statuses:
| id | status |
|---|---|
| 1 | paid |
| 2 | paid |
| 3 | cancelled |
| 4 | paid |
If the entire set of rows has been collapsed into one result row, which status should SQL show next to the total count?
paid?
pending?
cancelled?
SQL doesn't guess. You have to state the logic explicitly.
If you want one total count for all orders, remove status:
SELECT COUNT(*) AS orders_count
FROM orders;
If you want the number of orders for each status, add GROUP BY:
SELECT status, COUNT(*) AS orders_count
FROM orders
GROUP BY status;
The result now has one row for each status rather than one overall row:
| status | orders_count |
|---|---|
| paid | 86 |
| pending | 9 |
| cancelled | 11 |
| refunded | 14 |
We'll cover GROUP BY in detail next. For now, focus on why the error occurs:
an collapses the rows, while a regular column still has multiple possible values. SQL won't choose one of them for you.
The main rule for without GROUP BY
If a query has no GROUP BY, aggregate functions calculate a result across the entire set of rows left after WHERE.
SELECT COUNT(*), SUM(total_amount)
FROM orders
WHERE status = 'paid';
This query returns one row.
You can't place a regular column next to an aggregate without grouping:
SELECT status, COUNT(*)
FROM orders;
This query is invalid because status can have different values in different rows.
Interview question
Interview question:
A table has one hundred rows, and some values in the manager_id column are NULL. What will COUNT(*), COUNT(manager_id), and COUNT(DISTINCT manager_id) return, and why can the numbers differ?
Strong answer:
COUNT(*) returns 100 because it counts rows and doesn't care about NULL values in individual columns. COUNT(manager_id) returns a number less than or equal to 100: it counts only rows where manager_id has a value because COUNT(col) ignores NULL. COUNT(DISTINCT manager_id) returns the number of distinct non-null manager_id values, so it will be less than or equal to COUNT(manager_id). These answer three different questions: how many rows there are, how many rows have a manager, and how many distinct managers appear.
Interview question:
Why is SELECT status, COUNT(*) FROM orders without GROUP BY an error?
Strong answer:
Without GROUP BY, COUNT(*) collapses the entire set of rows into one summary row, while status is a regular column that may have different values across those rows. SQL doesn't guess which status to show next to the overall count. You must either remove status if you want one overall total or add GROUP BY status if you want a count for each status.
Interview question:
How does SUM(total_amount) differ from COUNT(*) on an empty set of rows?
Strong answer:
If no rows remain after WHERE, COUNT(*) returns 0 because there are zero rows. SUM(total_amount) returns NULL because there is nothing to add. If the report needs a zero total, you can wrap the in COALESCE(SUM(total_amount), 0.00).
SELECT AVG(price) FROM products; return if there is no GROUP BY?COUNT(*) count?COUNT(user_id) and COUNT(DISTINCT user_id)?SELECT status, COUNT(*) FROM orders; invalid without GROUP BY?QUERY: Raw rows show events. Aggregates show the pulse: how many, how much, the range, and the average rhythm.
- Number of Club ConcertsEASY
- Average Amount per Purchase EventMEDIUM
- Smallest and Largest PurchasesMEDIUM
SELECT * FROM orders;