Ben
Ben

Reputation: 62364

Simple SQL case issue - returning 0 when NULL

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

Upvotes: 4

Views: 17806

Answers (2)

Ike Walker
Ike Walker

Reputation: 65537

Use this syntax to replace NULLs with 0s:

select COALESCE(qty,0)...

Upvotes: 7

g.d.d.c
g.d.d.c

Reputation: 47988

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.

Upvotes: 11

Related Questions