VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
COUNT(*) answers how many rows. COUNT(DISTINCT column) answers how many
different values, which is usually the more interesting question about a column
you have not met.
Open the client with mysql -u root -p sakila before you start.
How COUNT DISTINCT works
COLUMN_NAME with the column whose different values you want counted,
and TABLE_NAME with the table. The server reads every row, throws away the
repeats, and counts what is left.
It is the count of what SELECT DISTINCT would
return, without returning it.
Examples
1) How many different values
2) Different combinations
Name several columns and a combination counts once, the same wayGROUP BY
treats them.
It skips NULL, which can make the answer look wrong
address2 is NULL in 4 rows and an empty string in the other 599.
SELECT COUNT(*) FROM address WHERE address2 IS NULL.
Summary
- Use
COUNT(DISTINCT column)to count different values rather than rows. - Name several columns to count distinct combinations.
- Expect NULL to be skipped, not counted as a value.
- Count the missing rows separately when you need both numbers.
See also
- Aggregate functions — the rest of the family
- SELECT DISTINCT — returning those values instead of counting them
- GROUP BY — counting per category
- MySQL GROUP BY performance — what deduplicating costs at scale

