Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing both null and not null in mysql query

Tags:

null

mysql

Let's say I have the table

NAME | ID | REF  
foo1 | 1 | NULL  
foo2 | 2 | 1234  
foo2 | 3 | 567  
foo1 | 4 | NULL  
foo3 | 5 | 89  

I'd like to count all instances of NULL and NOT NULL in one query so that I can say

NAME | null | not null  
foo1 |  0   |   2  
foo2 |  2   |   0  
foo3 |  0   |   1

I could run these two queries

select NAME,count(*) from TABLE where REF is not null  
select NAME,count(*) from TABLE where REF is null

But I'm sure there must be a simple way to do it in one mysql query.

like image 381
tomasz Avatar asked Dec 22 '22 09:12

tomasz


2 Answers

You can use SUM() on ISNULL() like this

select NAME, sum(isnull(REF)) as is_null, sum(not isnull(REF)) as is_not_null from TABLE group by NAME;

SUM(1) is equivalent to COUNT(*), so it will really make a count.

like image 64
Josh Davis Avatar answered Dec 29 '22 18:12

Josh Davis


If it is ok with a solution that uses grouping you can try something like:

SELECT ISNULL(ref),COUNT(*) FROM TABLE GROUP BY ISNULL(ref)

At least it tells you how many row with a NULL in ref you have. This solution (good or not) could be extended with a select of GROUP_CONCAT on NAME if you need to select every individual name.

like image 28
Fredrik Avatar answered Dec 29 '22 20:12

Fredrik