What are the purposes of the SELECT IF statement in MySQL?
In MySQL, the SELECT IF statement serves several purposes:
- IF function: The IF function can return different values based on conditions. The syntax is IF(condition, value_if_true, value_if_false), which returns value_if_true or value_if_false based on the condition’s value.
Create a new column called “age_category” which categorizes customers as either ‘adult’ or ‘minor’ based on their age being greater than or equal to 18.
- IFNULL function: The IFNULL function is used to check if a field value is NULL, and if it is, then return a specified value. The syntax is: IFNULL(expr1, expr2), where if expr1 is NULL, then expr2 is returned, otherwise expr1 is returned.
Example:
Choose the birthday or display ‘unknown’ if it is empty for customers.
- CASE statement: The CASE statement can return different values based on conditions. The syntax is: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE default_result END.
In the query, we select the id of customers and categorize them as either adults or minors based on their age.