Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count NULL in COUNT(column) query?

I have the following table that I’m trying to find the total count for each unique name element. The problem is, other: 1 and other: Null are supposed to be different elements, but my query is grouping them together. The issue I’m running into is that null is not being counted as a row. But when I use count(*), other: 1 and other: Null are grouped together.

Name id GroupId
Other 1 8
Other Null 8
Facebook 2 8
Google 3 8
Facebook 2 8

The goal is to return:

[{Other: 1}, {Other: 1}, {Facebook: 2}, {Google: 1}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried:

SELECT name, count(id) 
FROM table 
WHERE id IS NOT NULL 
AND groupId='${id}' 
GROUP BY name 
UNION 
SELECT name, count(*) 
FROM table 
WHERE id IS NULL 
AND groupId ='${id}' 
GROUP BY name

And:

SELECT name, count(id)
FROM table
WHERE id='${id}' 
GROUP BY name

How would I get the desired return value above?

>Solution :

You seem to want one result row per name and ID, so don’t group by name only, but by name and ID:

SELECT name, COUNT(*) 
FROM table 
WHERE groupId = '${id}' 
GROUP BY name, id
ORDER BY name, id;

As you don’t want to show the ID in your result, omit it from the select clause.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading