Skip to content
Advertisement

How to count number of groups?

I have a table as follow:

id    g_n   val_name  
---------------------
1      a      "a"
2      a      "aa"
3      b      "123"
4      b      "asad"
5      c      "aas1"

I want to count the number of distinct g_n. (Here it’s 3.)

I have tried with:

select count(*)
from table_t
group by g_n

But it gives me the number of items per group.

How can I count the number of distinct g_n?

Advertisement

Answer

Use count(distinct):

select count(distinct g_n)
from table_t;

There is no need to aggregate using group by for this result.

Note: This ignores NULL values. If you want to count them as well, then:

select count(distinct g_n) + max( (g_n is null)::int )
4 People found this is helpful
Advertisement