David Bélanger
David Bélanger

Reputation: 7438

IF inside a SWITCH CASE statement

I got the following query :

SELECT      ua.attribute_id, ma.attribute_name, ma.attribute_type, ma.attribute_default, ma.attribute_format,
    (CASE ma.attribute_type
        WHEN 0 THEN ua.attribute_default
        WHEN 1 THEN ua.attribute_bool
        WHEN 2 THEN ua.attribute_combo
        WHEN 3 THEN ua.attribute_decimal
        WHEN 4 THEN ua.attribute_integer
        WHEN 5 THEN ua.attribute_decimal
    END) AS attribute_value 
FROM        units_attributes AS ua
LEFT JOIN   models_attributes AS ma ON ma.attribute_id = ua.attribute_id
WHERE       ua.unit_id = 1

I want to put a IF for attribute_value. If attribute_value is NULL, then I want to use ua.attribute_default.

I have attempted to use a IF statement after the AS but it doesn't work...

Thanks.

Upvotes: 1

Views: 540

Answers (1)

Travesty3
Travesty3

Reputation: 14479

Instead of using IF, try using COALESCE(). It takes multiple parameters and returns the first non-null value.

COALESCE(attribute_value, ua.attribute_default)

Upvotes: 4

Related Questions