Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT() doesn't work with GROUP BY?

SELECT COUNT(*) FROM table GROUP BY column

I get the total number of rows from table, not the number of rows after GROUP BY. Why?

like image 282
thelolcat Avatar asked Dec 04 '25 13:12

thelolcat


1 Answers

Because that is how group by works. It returns one row for each identified group of rows in the source data. In this case, it will give the count for each of those groups.

To get what you want:

select count(distinct column)
from table;

EDIT:

As a slight note, if column can be NULL, then the real equivalent is:

select (count(distinct column) +
        max(case when column is null then 1 else 0 end)
       )
from table;
like image 54
Gordon Linoff Avatar answered Dec 07 '25 04:12

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!