Explain it simply
Explain it simply
Picture a shop's receipts for the day piled on a desk. "How many receipts?" is COUNT, "how much did we sell in total?" is SUM, and "what is the typical receipt worth?" is AVG. All three questions shrink a pile of paper into a single number.
Every "Total Users", "Revenue" and "Average order value" card on a dashboard comes from these three functions. The tricky part is blank (NULL) values: you only get the right number if you know which function counts them and which one skips them.
Problem → Why → Solution
The problem: is the average rating secretly inflated?
There are five orders, but only three customers left a rating (5, 4 and 3); the other two ratings are NULL. One report says "average rating 4.0" while another says 2.4. A query that counts orders with COUNT(rating) claims there are 3 orders, not 5. Which number is right?
SELECT COUNT(rating) AS order_count -- 3, but there are 5 orders
FROM orders;
SELECT AVG(rating) AS report_a, -- 4.0000000000000000
AVG(COALESCE(rating, 0)) AS report_b, -- 2.4000000000000000
SUM(rating) / COUNT(*) AS report_c -- 2 (integer division!)
FROM orders;Why do the numbers disagree?
COUNT(rating) counts only rows that have a rating. AVG(rating) drops the NULL rows from the denominator and computes 12 / 3 = 4, which is "the average among people who rated". COALESCE(rating, 0) treats a missing rating as a zero score and gets 12 / 5 = 2.4. Report C divides an integer by an integer, so the fraction is chopped off. You can only pick the right figure once you know which question each expression answers.
Core concept: how each function treats NULL
COUNT comes in three forms. COUNT(*) counts rows: it never looks at column values, so even a row full of NULLs counts once. COUNT(column) counts only the non-NULL values in that column. COUNT(DISTINCT column) removes duplicates among the non-NULL values and counts what is left. That makes COUNT(*) minus COUNT(rating) the number of orders still waiting for a rating.
SUM and AVG skip NULLs entirely. SUM adds up the non-NULL values. AVG equals SUM(column) divided by COUNT(column), not by COUNT(*). That is a decision with consequences: if NULL means "unknown", skipping is right; if it really means "zero", you must say so yourself with AVG(COALESCE(column, 0)).
When no rows survive WHERE, the functions part ways: COUNT returns 0, but SUM and AVG return NULL. That is why cards such as "revenue today" are usually written as COALESCE(SUM(amount), 0).
PostgreSQL also fixes the result types: COUNT returns bigint, SUM of an integer column returns bigint, and AVG of integers returns numeric, which is why you see 4.0000000000000000. Trim it for display with ROUND(AVG(x), 2). If you divide by hand, as in SUM(x) / COUNT(*), both sides are integers and the fraction is lost, so cast one side with ::numeric.
Aggregates can also be combined inside expressions. COUNT(*) - COUNT(rating) gives the number of unrated orders, and SUM(amount) / COUNT(DISTINCT customer_id) gives the average spend per customer. DISTINCT works inside SUM and AVG as well, but be careful: SUM(DISTINCT amount) adds two different orders of the same amount only once, so the revenue comes out too low. DISTINCT removes repeated values, not repeated rows, which is rarely what a money total needs.
- COUNT(*): count every row
- COUNT(col): count non-NULL values
- SUM(col): add non-NULL values
- AVG(col) = SUM(col) / COUNT(col)
- No rows: COUNT 0, SUM/AVG NULL
Only COUNT(*) sees NULL rows; every column-based aggregate looks straight past them.
General pattern
SELECT COUNT(*) AS row_count,
COUNT(column_name) AS non_null_count,
COUNT(DISTINCT column_name) AS distinct_count,
COALESCE(SUM(column_name), 0) AS total,
ROUND(AVG(column_name), 2) AS average,
COUNT(*) FILTER (WHERE condition) AS matching_rows
FROM table_name
WHERE condition;You can mix several aggregates in one SELECT, and they all read the same set of rows left after WHERE. COALESCE turns the NULL of an empty set into 0, ROUND trims the displayed decimals, and FILTER gives a single aggregate an extra condition of its own.
Example: dashboard numbers for an orders table
The orders table holds five orders. Customers 1 and 3 placed two orders each, and two ratings are NULL. One query computes the numbers for six dashboard cards.
SELECT COUNT(*) AS orders,
COUNT(rating) AS rated,
COUNT(DISTINCT customer_id) AS customers,
SUM(amount) AS revenue,
ROUND(AVG(amount), 2) AS avg_order,
ROUND(AVG(rating), 2) AS avg_rating
FROM orders;Code breakdown
- Line 1
SELECT COUNT(*) AS orders,Counts every row, giving 5, including the orders whose rating is NULL.
- Line 2
COUNT(rating) AS rated,Counts only the three non-NULL ratings, giving 3; 5 minus 3 means two orders are still unrated.
- Line 3
COUNT(DISTINCT customer_id) AS customers,The customer_id values are 1, 1, 2, 3, 3; removing duplicates leaves three distinct customers.
- Lines 4-5
ROUND(AVG(amount), 2) AS avg_order,SUM(amount) is 500.00 and AVG is 500.00 / 5 = 100.00. amount has no NULLs, so the denominator equals the row count.
- Line 6
ROUND(AVG(rating), 2) AS avg_rating(5 + 4 + 3) / 3 = 4.00, not divided by 5: the two NULL ratings are left out of the denominator.
orders | rated | customers | revenue | avg_order | avg_rating
--------+-------+-----------+---------+-----------+------------
5 | 3 | 3 | 500.00 | 100.00 | 4.00
(1 row)Empty results and integer division
No customer has customer_id 99. The first query below still returns one row: COUNT is 0, while SUM and AVG are NULL, shown as blanks in psql. The column wrapped in COALESCE shows 0. The second query fixes the integer division: casting with ::numeric gives 2.40 instead of 2.
SELECT COUNT(*) AS n,
SUM(amount) AS raw_sum,
AVG(amount) AS raw_avg,
COALESCE(SUM(amount), 0) AS safe_sum
FROM orders
WHERE customer_id = 99;
SELECT ROUND(SUM(rating)::numeric / COUNT(*), 2) AS per_order
FROM orders;Counting conditionally with FILTER
Say one card needs "orders not yet rated" and another needs "revenue from orders of 100 or more". WHERE affects the whole query, so it cannot serve both. FILTER (WHERE ...) applies to a single aggregate only. FILTER is standard SQL and works in PostgreSQL and SQLite, but not in MySQL or SQL Server; there, use SUM(CASE WHEN ... THEN 1 ELSE 0 END), shown in the third column.
SELECT COUNT(*) FILTER (WHERE rating IS NULL) AS unrated,
SUM(amount) FILTER (WHERE amount >= 100) AS big_order_revenue,
SUM(CASE WHEN rating IS NULL THEN 1 ELSE 0 END) AS unrated_portable
FROM orders;| Expression | Result |
|---|---|
| COUNT(*) FILTER (WHERE rating IS NULL) | 2 |
| SUM(amount) FILTER (WHERE amount >= 100) | 320.00 (120 + 200) |
| SUM(CASE WHEN rating IS NULL THEN 1 ELSE 0 END) | 2 |
In real projects
Where this shows up in real projects
The top cards of almost every admin dashboard follow this pattern: COUNT(*) for users, COALESCE(SUM(amount), 0) for this month's revenue, ROUND(AVG(amount), 2) for average order value. API endpoints use COUNT(*) for pagination to compute "page 1 of 12". Review systems usually show AVG(rating) together with COUNT(rating), as in "4.0 stars (3 reviews)".
For money, the column type matters: SUM over numeric is exact, while SUM over real or double precision can accumulate small rounding errors. PostgreSQL must actually visit rows to give an exact COUNT(*), so it can be slow on very large tables; when an estimate is good enough there are ways to read planner statistics instead, but financial reports should always use an exact count. Whatever the figure, write down next to it which rows it counts and how NULLs were treated, so two teams never publish different averages from the same table.
Common mistakes
Common mistakes
1. Counting rows with COUNT(column)
Asking "how many orders?" with COUNT(rating) silently drops the NULL ratings and gives 3 instead of 5. To count rows, use COUNT(*) or COUNT of a NOT NULL primary key such as order_id.
2. Assuming AVG treats NULL as 0
AVG(rating) is the average among people who rated. If the business wants a missing rating to count as 0, write AVG(COALESCE(rating, 0)) explicitly. State which meaning the report uses, because the two figures can differ wildly, like 4.0 versus 2.4.
3. Dividing two integers
SUM(rating) / COUNT(*) is bigint divided by bigint, so PostgreSQL truncates 2.4 to 2. SQL Server behaves the same, while MySQL's / returns a decimal. To be correct everywhere, cast one side with ::numeric or CAST(... AS numeric).
Mini challenge
Mini challenge: support ticket summary
The tickets table holds six tickets. Resolved tickets have minutes (time to resolve), and tickets that are still open have NULL. Write a one-row report for the support manager.
- total_tickets: how many tickets exist
- resolved: tickets with minutes; still_open: tickets where it is NULL (use FILTER)
- total_minutes: the total time spent resolving
- avg_minutes: the average over resolved tickets, rounded to 1 decimal
SELECT
-- TODO: total_tickets (every row)
-- TODO: resolved (non-NULL minutes)
-- TODO: still_open (FILTER on minutes IS NULL)
-- TODO: total_minutes
-- TODO: avg_minutes rounded to 1 decimal
FROM tickets;Expected: One row: total_tickets | resolved | still_open | total_minutes | avg_minutes ---------------+----------+------------+---------------+------------- 6 | 4 | 2 | 107 | 26.8 (1 row)
Show hint
COUNT(*) for every row, COUNT(minutes) for resolved ones. AVG(minutes) already leaves the NULL tickets out, so it directly gives the average of the four resolved tickets (107 / 4).
Show solution
SELECT COUNT(*) AS total_tickets,
COUNT(minutes) AS resolved,
COUNT(*) FILTER (WHERE minutes IS NULL) AS still_open,
SUM(minutes) AS total_minutes,
ROUND(AVG(minutes), 1) AS avg_minutes
FROM tickets;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- COUNT(*) counts rows; COUNT(column) counts only non-NULL values.
- SUM and AVG skip NULLs, and AVG divides by COUNT(column), not COUNT(*).
- With no rows, COUNT gives 0 but SUM/AVG give NULL, so add a default with COALESCE.
- Cast with ::numeric before dividing integers, and use FILTER to give one aggregate its own condition.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group