0

I have a query in SQL which sum values and add them as months to a date.

    SELECT
    FROM_UNIXTIME(S.created) as start_date, 
   (FROM_UNIXTIME(S.created) + INTERVAL (C.items_left + C.items_given) MONTH)
    AS end_date,
    FROM table1 S
    LEFT JOIN table2 C ON C.id = S.id;

The problem arises when some of these values to sum are null instead of 0 and I am not able to change the source of data.

(FROM_UNIXTIME(S.created) + INTERVAL (C.items_left + C.items_given) MONTH)
AS end_date,

is generating nulls because (C.items_left + C.items_given) is null.

So, the question is, how do I execute this sum so the result is 0 instead of null?

1
  • 1
    coalesce should help Commented Feb 22, 2019 at 12:25

2 Answers 2

2

use coalesce

SELECT
    FROM_UNIXTIME(S.created) as start_date, 
   ( coalesce(FROM_UNIXTIME(S.created),0) + INTERVAL coalesce((coalesce(C.items_left,0) + coalesce(C.items_given,0)),0) MONTH)
    AS end_date,
    FROM table1 S
    LEFT JOIN table2 C ON C.id = S.id;
Sign up to request clarification or add additional context in comments.

4 Comments

Anyway I just put it in the sum coalesce(C.items_left + C.items_given), as it's the only source of null data.
@Belen you can it inner as well for both items_left and items_given
@Belen inner is safe otherwise if items_left null and items_given has value in that case null+val also make it null
@zaybul, agreed, I'm going with your query, it works perfect as it is. Thanks!
2

Use COALESCE():

(FROM_UNIXTIME(S.created) + INTERVAL (COALESCE(C.items_left, 0) + COALESCE(C.items_given, 0)) MONTH)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.