Icon View Thread

The following is the text of the current message along with any replies.
Messages 1 to 5 of 5 total
Thread Records containing Null value in a SQL calculation
Mon, Sep 29 2014 10:41 AMPermanent Link

Geir Bratlie

When running the query:

SELECT  SUM(field1 + field2 – field3) as sumfields

where some fields in records have Null values, the calculation returns wrong answer.
It seems that null is not always treated as value 0. (Datatype is Currency - I have not tried other datatypes)

If I run:
UPDATE myTable SET field1=0 WHERE field1=null;

I then get the right answer when running the first query again.


Regards,
Geir Bratlie
Mon, Sep 29 2014 12:12 PMPermanent Link

Jose Eduardo Helminsky

HPro Informatica

Geir Bratlie

<<
When running the query:

SELECT  SUM(field1 + field2 – field3) as sumfields

where some fields in records have Null values, the calculation returns wrong answer.
It seems that null is not always treated as value 0. (Datatype is Currency - I have not tried other datatypes)
>>
In SQL every operation with NULL always return NULL and this is not an error.

To avoid this situation and solve "your" situation for every field that can be null you must use COALESCE

SELECT  SUM(coalesce(field1,0 + coalesce(field2,0) – coalesce(field3,0)) as sumfields

The function COALESCE works like if there is NULL there assume "0" (zero) or anything else you want.

Eduardo (HPro)
Tue, Sep 30 2014 3:07 AMPermanent Link

Roy Lambert

NLH Associates

Team Elevate Team Elevate

Geir


I'll go along with Jose about using COALESCE to prevent the problem but out of interest what was the error?

Roy Lambert
Thu, Oct 2 2014 4:25 PMPermanent Link

Geir Bratlie

The query resultet in a wrong sum

In this case the right summery was abt 800.000, and it resultet in abt 780.000 bacause of some null values.

After setting all NULL values to "0", the summary was correct.

In my opinion, Null should be calculated as "0" if it is a numberic field.

-Geir-
Fri, Oct 3 2014 4:51 AMPermanent Link

Roy Lambert

NLH Associates

Team Elevate Team Elevate

Geir


>In my opinion, Null should be calculated as "0" if it is a numberic field.

DO NOT repeat NOT get me started on the behaviour of nulls and sql - if you do you'll regret it!

Roy
Image