1

I have the following stored procedure

BEGIN
SELECT kids.*, SUM(point) as `point_sum`
FROM kids
    LEFT JOIN tasks
    ON kids.id = tasks.kid_id
WHERE kids.user_id = IN_user_id
GROUP BY kids.name;
END

This statement works fine.

My Question: the SUM(point) for new users are typically NULL because there is no submitted value yet to be summed. What I want is if SUM(point) is NULL then it should return value like 0 but otherwise it should present the sum. I have looked around and not sure how to fix it, any good ideas?

1
  • 1
    Use IFNULL or COALESCE -- coalesce(sum(point),0)... Commented Dec 4, 2014 at 17:31

2 Answers 2

1

You could use the coalesce function:

SELECT kids.*, COALESCE(SUM(point), 0) as `point_sum`
FROM kids
    LEFT JOIN tasks
    ON kids.id = tasks.kid_id
WHERE kids.user_id = IN_user_id
GROUP BY kids.name;
Sign up to request clarification or add additional context in comments.

Comments

1

All you really need is IFNULL():

SELECT kids.*, IFNULL(SUM(point), 0) AS point_sum

That converts NULL to the supplied value, in this case 0.

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.