Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to add values of two columns containing null values?

Given table:

    ID   ONE   TWO
    X1   15    15
    X2   10    -
    X3   -     20

This query:

SELECT (ONE + TWO) FROM (TABLE)

Just returns the sum of X1's values but not the others since at least one column has a null value. How can I still add them even if there is a null? i.e. consider the null as a 0 maybe?

like image 308
antonpug Avatar asked Mar 27 '12 18:03

antonpug


1 Answers

SELECT (COALESCE(ONE, 0) + COALESCE(TWO, 0)) FROM (TABLE) 

COALESCE will return the first non-null value found in the parameters from left to right. So, when the first field is null, it will take the 0.

That way, X2 will result in 10 + 0 = 10

like image 72
Mosty Mostacho Avatar answered Sep 26 '22 11:09

Mosty Mostacho