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
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) ...
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.
If a grouping column contains null values, all null values are considered equal, and they are put into a single group.
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
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