tags:

views:

35

answers:

2

Apparently NUMBER + NULL returns NULL in SQL. So I need it to add 0 instead of NULL but this isn't working, I'm getting a syntax error. I'm looking at the docs and this is what it says to do so I'm not sure...

SELECT sku, (qty + (SELECT
(CASE qty WHEN IS NULL THEN 0 ELSE qty END)
FROM other WHERE sku = Sheet1.sku LIMIT 1)) as qty
FROM Sheet1 WHERE sku != '' ORDER BY sku ASC

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IS NULL THEN 0 ELSE qty END) FROM other WHERE sku = Sheet1.sk
+4  A: 

You're really close.

Case qty When NULL Then 0 else qty END

The IS Null is a Where Clause Convention. You can also use Coalesce:

Select Coalesce(qty, 0)

Coalesce returns the 1st non-null of it's parameter list. So if qty is Null you get 0, otherwise you get qty.

g.d.d.c
Maybe this is dialect-dependent, but "case qty when null then 0 else qty end" doesn't work the way you are apparently expecting in Postgres. The WHEN clause is equivalent to saying "if null=null", which gives a result of null, which is not true, so you get the else clause, which will return null, thus defeating the purpose of the CASE construct. It works if you say "case when qty is null then 0 else qty end". In any case, the COALESCE does indeed work and is, I think, much clearer and easier to read.
Jay
+2  A: 

Use this syntax to replace NULLs with 0s:

select COALESCE(qty,0)...
Ike Walker