MySQL COUNT() Function
MySQL COUNT() Function: Counting Rows and Non-NULL Values
The COUNT() aggregate function returns the number of rows or non-NULL column values in a query result. It is one of the most frequent tools in reporting, pagination, and audit queries.
Unlike SUM() or AVG(), COUNT() never returns NULL when a table or filtered group has zero matching rows. Instead, it always returns 0 as a BIGINT.
Syntax
COUNT(*)
COUNT(expr)
COUNT(DISTINCT expr)
COUNT(*): Counts every row in the group, even if all columns containNULL.COUNT(expr): Counts only rows whereexprevaluates to a non-NULLvalue.COUNT(DISTINCT expr): Counts unique non-NULLvalues ofexpr.
Practical Example
Suppose demo_customers stores customer accounts, and referrer_id is NULL for direct signups. You can compare total signups, referred signups, and unique referrers per country in one query.
SELECT
country,
COUNT(*) AS total_customers,
COUNT(referrer_id) AS referred_customers,
COUNT(DISTINCT referrer_id) AS unique_referrers
FROM demo_customers
GROUP BY country;
| country | total_customers | referred_customers | unique_referrers |
|---|---|---|---|
| Canada | 45 | 18 | 11 |
| Japan | 20 | 0 | 0 |
| Germany | 32 | 12 | 9 |
In Japan, 20 customers exist, none have a referrer_id, and both COUNT(referrer_id) and COUNT(DISTINCT referrer_id) return 0 rather than NULL.
Common Mistakes & NULL Behavior
- Assuming COUNT(col) equals COUNT(*):
COUNT(col)silently skipsNULLvalues. UseCOUNT(*)whenever you want total row count, regardless of nullable columns. - Expecting NULL on empty tables: When a
WHEREclause matches zero rows and there is noGROUP BY,COUNT(*)returns0, notNULL. (WithGROUP BY, empty groups simply produce no output rows.) - Thinking COUNT(1) is faster than COUNT(*): Modern MySQL optimizes
COUNT(*)andCOUNT(1)identically in InnoDB. PreferCOUNT(*)for clarity. - Conditional counting trap: Writing
COUNT(CASE WHEN status = 'paid' THEN 1 ELSE 0 END)counts every row because0is non-NULL. OmitELSE 0(so unmatched rows becomeNULL) or useSUM(status = 'paid').
Frequently Asked Questions
What does COUNT(col) return when every row in that column is NULL?
It returns 0. COUNT() counts only non-NULL entries, so zero non-NULL entries produce 0.
Can I pass multiple columns to COUNT(DISTINCT)?
Yes! MySQL supports COUNT(DISTINCT col1, col2), which counts unique non-NULL pairs where neither col1 nor col2 is NULL.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.