Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Sql Sum of multiple columns containing nulls return incorrect result?

Table containing the following values:

Column1  Column2
1        NULL
NULL     4
2        NULL
NULL     5
3        6

The following query:

SELECT 
    SUM([Column1] + [Column2] ) 
FROM [myTable]

returns a value of 9 when it should be returning 21. Why? How does it arrive at the value?

I know the SUM can be corrected by adding ISNULL like so:

SELECT 
    SUM(ISNULL([Column1], 0) + ISNULL([Column2], 0)) 
FROM [myTable]

but I would like to know the logic behind the value 9

like image 481
Gary Barrett Avatar asked Oct 30 '12 03:10

Gary Barrett


People also ask

Does sum ignore NULL values in 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) ...

What happens if you add NULL in SQL?

If there is a value in the Title column, you add a space to it and return it. If the Title column has no value, then NULL , when added to a string with a space in it, still results in a NULL , and so the COALESCE function examines the next parameter in the list and returns the blank string.

What happens if nulls exist in the grouping attribute of the query?

If a grouping column contains null values, all null values are considered equal, and they are put into a single group.


1 Answers

use COALESCE to convert null into 0. (that's it if you want null values as zero.)

SELECT SUM(COALESCE(column1,0) + COALESCE(column2,0))
FROM table1
  • See SQLFIDDLE Demo
like image 115
John Woo Avatar answered Sep 24 '22 20:09

John Woo