COUNT example
SELECT COUNT(*) AS total_customers,
COUNT(email) AS customers_with_email,
COUNT(DISTINCT city) AS distinct_cities
FROM customers;| total_customers | customers_with_email | distinct_cities |
|---|---|---|
| 12 | 9 | 6 |
The table contains 12 rows. Three customers have email = NULL, which is why COUNT(email) returns 9. London, Manchester, Bristol, Leeds, Birmingham and Edinburgh are six distinct cities.
Check the result with small data
We count every row, and then only the rows that have an email address.
WITH customers(name, email) AS (
VALUES ('Amy','a@test.local'), ('Liam',NULL), ('Eva','e@test.local')
)
SELECT COUNT(*) AS rows, COUNT(email) AS with_email
FROM customers;| rows | with_email |
|---|---|
| 3 | 2 |
COUNT(*) returns 3; COUNT(email) returns 2 because it ignores NULL. That difference is crucial when data is missing.
Check your understanding: What would with_email be if Eva's email address were NULL?
Show answer
1. COUNT(email) ignores NULLs, so it would only count Amy's email. COUNT(*) would still be 3.
What changes from case to case
What happens when there are no rows
SELECT COUNT(*) AS very_expensive_products
FROM products
WHERE price > 2000;The result is 0. Unlike other aggregates such as SUM, COUNT returns zero when the set contains no rows.
Avoid counting rows multiplied by a JOIN
Once a customer row is matched to several orders, the customer appears once per order. COUNT(*) counts rows in the result, not unique customers. If the question is “how many customers appear?”, you may need COUNT(DISTINCT c.id).
Before counting, name the entity. Are you counting rows, orders, customers with an email, distinct products or groups? That phrase usually tells you which expression belongs inside COUNT.
Defining a report's denominator
A count needs a unit: rows, orders, customers or known values. COUNT(*) counts the rows in the set it receives; COUNT(column_name) counts those with a non-null value in that column. An empty string is still a value and can be included in the second count. COUNT(DISTINCT column_name) answers a different question: how many distinct known values there are.
The input set matters as much as the function. Joining orders to order lines can produce several rows per order, and counting them as orders inflates the metric. To check, list their ids before grouping and compare the size of the detail with the unit the report claims to measure. Do not use a distinct count to hide a faulty join condition.
In an aggregate with no grouping over zero rows, COUNT returns zero. With grouping, a category with no rows may not appear at all. If the report must show every category, including those with zero, you need to build that full list and relate it to the transactions. In an outer join, count a required key from the right side so the padded row is not counted as a real order.
Technical questions: PostgreSQL: aggregate functions (opens in a new tab).