I have a SQL query which includes the following statement
SELECT
(CASE
WHEN field1 > 0 THEN field1
ELSE (field2 * field3)
END) AS result
FROM table
Which is supposed to return the value of field1, unless that is ‘0’, in which case the statement returns the product of two other fields.
The issue I am having is this statement returns NULL if field1 is NULL.
I want to revise my SQL so that the product of fields 2 & 3 is returned when field1 is NULL, just as it does when field1 is ‘0’.
I have tried the following:
SELECT
(CASE
WHEN field1 > 0 THEN field1
WHEN field1 IS NULL THEN (field2 * field3)
ELSE (field2 * field3)
END) AS result
FROM table
But NULL still seems to permeate through the statement and NULL is still being returned whenever field1 is NULL.
Your query does already what you want. When
field1isNULL, it returns the productfield2 * field3. If either offield2orfield3though isNULL, the (returned) product will beNULL.If you want to be returning some value (
0perhaps) when either of them isNULL, you can change theCASE:or simply: