11

Hello I have a colleague who always writes ISNULL(COUNT(*),0), but I always thought that COUNT(*) could never return NULL.

But then I searched the interwebs and my findings allowed me to write this little piece of code:

create table t1 (
    val1 varchar(50),
)

select count(*) from t1
where val1 like 'abc'
group by val1

Are there any other cases when COUNT(*) returns NULL?

DonkeyMaster
  • 1,302
  • 4
  • 17
  • 36

3 Answers3

15

It doesn't return NULL. The GROUP BY in your example makes it return no rows at all, which is not the same as a NULL in a column.

Lucero
  • 59,176
  • 9
  • 122
  • 152
  • Just a note. If you were looking to do this in an update statement, for example:

    update t2 set col1=select count(*) from t1 where val1 like 'abc' group by val1 the solution would be to wrap that in an IsNull, like this: update t2 set col1=IsNull((select count(*) from t1 where val1 like 'abc' group by val1),0)
    – Frank Conry Aug 03 '13 at 20:47
2

That example doesn't return NULL. It returns no rows at all because of the GROUP BY on an empty set.

COUNT(*) cannot return a NULL. So the ISNULL is unnecessary.

Cade Roux
  • 88,164
  • 40
  • 182
  • 265
0

ISNULL it not needed it will return a number

James Kyburz
  • 13,775
  • 1
  • 32
  • 33