Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does COUNT(*) return NULL?

Tags:

sql

sql-server

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?

like image 756
DonkeyMaster Avatar asked Apr 07 '11 16:04

DonkeyMaster


People also ask

Does COUNT (*) return 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.

Does COUNT * COUNT NULL?

COUNT(*) returns the number of items in a group. This includes NULL values and duplicates.

What does COUNT (*) return if there are no rows?

COUNT() function It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

What does the COUNT (*) command return?

The COUNT(*) function returns a number of rows in a specified table or view that includes the number of duplicates and NULL values.


2 Answers

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.

like image 189
Lucero Avatar answered Oct 21 '22 07:10

Lucero


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.

like image 29
Cade Roux Avatar answered Oct 21 '22 08:10

Cade Roux