tags:

views:

3303

answers:

5

I can select all the distinct values in a column in the following 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?

+3  A: 

select Count(distinct columnName) as columnNameCount from tableName

Wayne
You're giving an alias to the table when I think you mean the column?
Mike Woodhouse
Yup.. edited. Thanks :)
Wayne
+25  A: 

You should be able to use this:

SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name

This will count only the distinct values for that column.

Noah Goodrich
Neat, i didn't know you could put the distinct keyword there.
Christian Oudard
As an aside, if you are going to use this value for anything in code and you use associative arrays to access the values from a query, you'll probably want to alias the column.
Noah Goodrich
perhaps to edit that in there for posterity?
Christian Oudard
+3  A: 
SELECT COUNT(DISTINCT column_name) FROM table as column_name_count;

you've got to count that distinct col, then give it an alias.

Pete Karl II
+3  A: 

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
/
David Aldridge
A: 

select count(*) from ( SELECT distinct column1,column2,column3,column4 FROM abcd ) T

This will give count of distinct group of columns.