2

I have a table TEST_TABLE as follows:

Name     x_col       y_col
=======================
Jay     NULL     2

This is a simplistic representation of a much larger issue but will suffice.

When I do the following query I get NULL returned

SELECT SUM(x_col + y_col) FROM TEST_TABLE WHERE Name='Jay'

I want it to be 2. I thought the SUM() method ignores NULL values. How can I ignore values that are null in this query? Or actually in general, as this is a problem for a lot of my algorithms.

2
  • sum(coalesce(x_col, 0) + coalesce(y_col, 0))? Commented May 29, 2020 at 10:46
  • 1
    @arsenal88 . . . I removed the inconsistent database tags. However, your question regards standard SQL so the database doesn't actually matter. Commented May 29, 2020 at 10:48

2 Answers 2

4

You get NULL because NULL + 2 returns NULL. The SUM() has only one row, and if the + expression is NULL, then the SUM() returns NULL.

If you want NULL to be treated as 0, the use COALESCE():

SELECT SUM(COALESCE(x_col, 0) + COALESCE(y_col, 0))
FROM TEST_TABLE
WHERE Name = 'Jay';

One final note. If you start with your data and filtered out all rows, then the result will still be NULL. To get 0, you need an additional COALESCE():

SELECT COALESCE(SUM(COALESCE(x_col, 0) + COALESCE(y_col, 0)), 0)
FROM TEST_TABLE
WHERE Name = 'Jayden';
Sign up to request clarification or add additional context in comments.

Comments

0

Use COALESCE to replace NULL with 0.

SELECT sum(coalesce(x_col, 0) + coalesce(y_col, 0)) FROM TEST_TABLE WHERE Name='Jay'

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.