Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does SUM(...) on an empty recordset return NULL instead of 0?

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.

like image 767
Heinzi Avatar asked Oct 04 '12 15:10

Heinzi


People also ask

Why sum returns a NULL in SQL?

If there are no rows, sum() will return null . It will also return null if all rows have a null balance.

How do you change NULL to zero in SQL?

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.

Is NULL in sum SQL?

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) ...

Does sum ignore nulls?

The SUM function returns the sum of the input column or expression values. The SUM function works with numeric values and ignores NULL values.


1 Answers

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.

like image 91
TToni Avatar answered Oct 02 '22 20:10

TToni