In this article, you’ll learn how to count the number of unique values in a column.
Let’s say we’ve got a table called “product” that looks like this:
We want to find the number of unique category values.
How can we do that?
SELECT COUNT(DISTINCT category) AS count_category FROM product;
The result of this query is:
It shows a value of 4 because there are 4 different category values:
Some values are repeated, but the repeated values are ignored in the COUNT function because we have used the DISTINCT keyword.
DISTINCT then COUNT
In the solution, the DISTINCT keyword goes inside the COUNT function.
What if you use the DISTINCT keyword outside of the COUNT function?
SELECT DISTINCT COUNT(category) AS count_category FROM product;
The result would be:
Why does it show 6?
The COUNT function is written as COUNT(category), so it counts the number of values in the category column, which is 6.
Then, the DISTINCT keyword eliminates duplicates that are returned by the function. But, the function only returns one row: a number of 6. There are no duplicates of this.
Putting the DISTINCT outside the COUNT will run the COUNT function first and then find unique values returned by COUNT, but there is only one value returned by COUNT. Using a DISTINCT COUNT is almost always unnecessary.
Putting the DISTINCT inside the COUNT will count the number of distinct values, which is what you want to do.