Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

SQL to find the number of distinct values in a column

I can choose every one of the distinct values in a column in the accompanying ways:
SELECT DISTINCT column_name FROM table_name;
SELECT column_name FROM table_name GROUP BY column_name;

But how do I get the row count from that query? Is a subquery required?
by

3 Answers

akshay1995
You can use the DISTINCT keyword within the COUNT aggregate function:

SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name

This will count only the distinct values for that column.
sandhya6gczb
This will give you BOTH the distinct column values and the count of each value.

SELECT [columnName], count([columnName]) AS CountOf
FROM [tableName]
GROUP BY [columnName]
pankajshivnani123
Be aware that Count() ignores null values, so if you need to allow for null as its own distinct value you can do something tricky like:

select count(distinct my_col)
+ count(distinct Case when my_col is null then 1 else null end)
from my_table
/

Login / Signup to Answer the Question.