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
?
COUNT never returns null. The following example calculates, for each employee in the employees table, the moving count of employees earning salaries in the range 50 less than through 150 greater than the employee's salary.
COUNT(*) returns the number of items in a group. This includes NULL values and duplicates.
COUNT() function It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.
The COUNT(*) function returns a number of rows in a specified table or view that includes the number of duplicates and NULL values.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With