Lesson

MySQL COUNT() Function

10 min reading
Free Course

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 contain NULL.
  • COUNT(expr): Counts only rows where expr evaluates to a non-NULL value.
  • COUNT(DISTINCT expr): Counts unique non-NULL values of expr.

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 skips NULL values. Use COUNT(*) whenever you want total row count, regardless of nullable columns.
  • Expecting NULL on empty tables: When a WHERE clause matches zero rows and there is no GROUP BY, COUNT(*) returns 0, not NULL. (With GROUP BY, empty groups simply produce no output rows.)
  • Thinking COUNT(1) is faster than COUNT(*): Modern MySQL optimizes COUNT(*) and COUNT(1) identically in InnoDB. Prefer COUNT(*) for clarity.
  • Conditional counting trap: Writing COUNT(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) counts every row because 0 is non-NULL. Omit ELSE 0 (so unmatched rows become NULL) or use SUM(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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum