Skip to main content

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

Replace 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

1,000 films drawn from 5 ratings.

2) Different combinations

Name several columns and a combination counts once, the same way GROUP BY treats them.
5 ratings times 3 rates, and every combination occurs. A row where any of the named columns is NULL is not counted at all.

It skips NULL, which can make the answer look wrong

address2 is NULL in 4 rows and an empty string in the other 599.
The answer is 1. The empty string is 1 distinct value, and the NULLs are skipped rather than counted as a value of their own. So “how many different things are in this column” is not what the function answers when some rows are empty: it answers “how many different values”, and NULL is the absence of one. When you need both numbers, count the missing rows with a second query: 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