Home > Software engineering >  Return the value of if statement in case when it's not null
Return the value of if statement in case when it's not null

Time:07-18

How to return the value of my expression when it's true

SELECT if(((SELECT SUM(kcal) 
from jadlospis 
WHERE data ="2022-07-18" and uzytkownik_id=1 
GROUP BY DAY(data)) as expr) IS NULL,expr,'0') 
#1064 - Something is wrong in your syntax obok 'as expr) IS NULL,expr,'0') LIMIT 0, 25' w linii 4.

How can i resolve my problem?

CodePudding user response:

You cannot use an alias in the IF() function. Repeat the full expression instead. Besides , redundant parenthesis can be removed. Try this:

SELECT if(
    (SELECT SUM(kcal) 
    from jadlospis 
    WHERE data ="2022-07-18" and uzytkownik_id=1 
    GROUP BY DAY(data)
    ) IS NULL,  -- don't use an alias
    (SELECT SUM(kcal) 
    from jadlospis 
    WHERE data ="2022-07-18" and uzytkownik_id=1 
    GROUP BY DAY(data)
    ), -- repeat the full expression 
    '0'
        ) 
;

-- in this case, it's better to use the IFNULL(expr1,expr2) function which returns expr1 if it is not null ,otherwise returns expr2 .
SELECT ifnull(
    (SELECT SUM(kcal) 
    from jadlospis 
    WHERE data ="2022-07-18" and uzytkownik_id=1 
    GROUP BY DAY(data)
    ) ,  
    '0'
        ) 
;

CodePudding user response:

According to this syntax IF(condition, true_value, false_value), if the condition is true 'true_value' will be returned. In your case, 'true_value' is NULL because the expression 'expr' upon being true returns NULL as per your condition.

  • Related