I understand why null + 1
or (1 + null
) returns null
: null
means "unknown value", and if a value is unknown, its successor is unknown as well. The same is true for most other operations involving null.[*]
However, I don't understand why the following happens:
SELECT SUM(someNotNullableIntegerField) FROM someTable WHERE 1=0
This query returns null
. Why? There are no unknown values involved here! The WHERE clause returns zero records, and the sum of an empty set of values is 0
.[**] Note that the set is not unknown, it is known to be empty.
I know that I can work around this behaviour by using ISNULL
or COALESCE
, but I'm trying to understand why this behaviour, which appears counter-intuitive to me, was chosen.
Any insights as to why this makes sense?
[*] with some notable exceptions such as null OR true
, where obviously true
is the right result since the unknown value simply does not matter.
[**] just like the product of an empty set of values is 1
. Mathematically speaking, if I were to extend $(Z, +)$ to $(Z union {null}, +)$, the obvious choice for the identity element would still be 0
, not null
, since x + 0 = x
but x + null = null
.
If there are no rows, sum() will return null . It will also return null if all rows have a null balance.
Use IFNULL or COALESCE() function in order to convert MySQL NULL to 0. Insert some records in the table using insert command. Display all records from the table using select statement.
In MySQL, SUM() is supposed to ignore null values. In any case, if you want to be specific, you can instruct the SQL Optimiser to substitute the null values with the value of 0. To do that, you can help yourself with the COALESCE() function and the following model: SELECT COALESCE(SUM(column_name), 0) ...
The SUM function returns the sum of the input column or expression values. The SUM function works with numeric values and ignores NULL values.
The ANSI-SQL-Standard defines the result of the SUM of an empty set as NULL. Why they did this, I cannot tell, but at least the behavior should be consistent across all database engines.
Reference: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt on page 126:
b) If AVG, MAX, MIN, or SUM is specified, then
Case: i) If TXA is empty, then the result is the null value.
TXA is the operative resultset from the selected column.
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