Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping null and empty values as one in sql

Tags:

sql

I have a query which provides a breakdown of different categories applied to things in the database:

select categories, count(*) from products 
group by categories

The data comes like this:

NULL                56
                    42
FooCategory         12
BlahCategory        2

I would like to group NULL and <blank>

NoCategory          98
FooCategory         12
BlahCategory        2
like image 361
birdy Avatar asked May 08 '26 10:05

birdy


2 Answers

try

select ISNULL(categories,'') as Categories, count(*) from products 
group by ISNULL(categories,'')

UPDATE

see here for parameters required

ISNULL ( check_expression , replacement_value )

like image 113
AbstractChaos Avatar answered May 10 '26 00:05

AbstractChaos


try

select categories, 
case when categories is null or categories = ' ' 
then 'noCategory' else categories end as grouped,
count(*) 
from products 
group by grouped
like image 29
Beth Avatar answered May 10 '26 01:05

Beth



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!