How to sum values from COALESCE with NULL values

1k Views Asked by At

I was wondering if it is possible to sum values used in coalesce even though some of them are null. Currently, if any value from coalesce returns null, the result of the sum is null as well.

Here is a SQL fiddle with the basic case: http://sqlfiddle.com/#!17/9eecb/83134

CREATE TABLE IF NOT EXISTS table1 (
   item_a INT,
   item_b INT,
   item_c INT
);

CREATE TABLE IF NOT EXISTS table2 (
   item_a INT,
   item_b INT,
   item_c INT
);

INSERT INTO table1(item_a, item_b, item_c)
VALUES (3, NULL, NULL);
INSERT INTO table2(item_a, item_b, item_c)
VALUES (NULL, 2, NULL);

SELECT (NULLIF(COALESCE (t1.item_a, t2.item_a),0) +
       NULLIF(COALESCE (t1.item_b, t2.item_b),0) +
       NULLIF(COALESCE (t1.item_c, t2.item_c),0)) as item_sum,
       COALESCE (t1.item_a, t2.item_a) as item_a,
       COALESCE (t1.item_b, t2.item_b) as item_b,
       COALESCE (t1.item_c, t2.item_c) as item_c
FROM table1 t1, table2 t2

The previous query should return 5 as item_sum (3 + 2). However, the last column item_c in both tables is null, so the result is NULL instead of 5.

Thanks

1

There are 1 best solutions below

0
id'7238 On

COALESCE

The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display

SELECT COALESCE (t1.item_a, t2.item_a, 0) +
       COALESCE (t1.item_b, t2.item_b, 0) +
       COALESCE (t1.item_c, t2.item_c, 0) as item_sumA,
       COALESCE (t1.item_a, t2.item_a) as item_a,
       COALESCE (t1.item_b, t2.item_b) as item_b,
       COALESCE (t1.item_c, t2.item_c) as item_c
FROM table1 t1, table2 t2

fiddle