Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does count(1/null) work but count(null/null) doesn't?

I saw this example in a presentation lately. When you run a query like this:

SELECT COUNT(NULL)

You get the following error:

Operand data type NULL is invalid for count operator.

When you run this:

SELECT COUNT(1/NULL)

You get 0 as a result, even though the division itself yields NULL as a result. Same happens if you swap the 1 and NULL.

But if you do this:

SELECT COUNT(NULL/NULL)

You get the same error as the first query again (the division itself is legit, yields NULL).

Can anyone explain how sql server works to give these kind of results?

like image 371
Hanneke Debie Avatar asked Jun 12 '26 16:06

Hanneke Debie


1 Answers

In SQL Server certain aggregate functions such as COUNT, MIN, MAX and functions such as DATEADD require a datatype. NULL, on its own, does not have one so this gives you an error:

SELECT COUNT(NULL) -- Operand data type NULL is invalid for count operator.

Likewise for:

SELECT COUNT(NULL/NULL)

For 1/NULL the datatype is INT and the value is NULL so this works:

SELECT COUNT(1/NULL) -- 0

Likewise for:

SELECT COUNT(CAST(NULL AS INT)) -- 0
like image 143
Salman A Avatar answered Jun 15 '26 05:06

Salman A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!