Control flow functions in MySQL help you execute different actions based on certain conditions. These functions allow you to add conditional logic directly into your SQL queries, similar to conditional statements in programming languages.
The IF() function returns a value based on a condition. If the condition is true, it returns one value; if false, it returns another.
SELECT IF(condition, true_value, false_value);
SELECT IF(salary > 5000, 'High Salary', 'Low Salary') AS SalaryCategory FROM employees;
SalaryCategory |
---|
High Salary |
Low Salary |
The IFNULL() function returns the first argument if it is not NULL; otherwise, it returns the second argument.
SELECT IFNULL(expression, default_value);
SELECT IFNULL(bonus, 0) AS BonusAmount FROM employees;
If the bonus column has a NULL value, it will return 0 instead of NULL.
The NULLIF() function returns NULL if two expressions are equal; otherwise, it returns the first expression.
SELECT NULLIF(expression1, expression2);
SELECT NULLIF(5000, 5000) AS Result;
Result |
---|
NULL |
If the two values are equal, it returns NULL. Otherwise, it returns the first value.
The COALESCE() function returns the first non-NULL value from the list of arguments. If all arguments are NULL, it returns NULL.
SELECT COALESCE(expression1, expression2, ...);
SELECT COALESCE(bonus, salary, 0) AS Value FROM employees;
This will return the bonus if it’s not NULL, otherwise the salary, and if both are NULL, it will return 0.
Function | Description |
---|---|
IF() | Returns one value if a condition is true, another if false. |
IFNULL() | Returns the first argument if not NULL, otherwise the second argument. |
NULLIF() | Returns NULL if two expressions are equal, otherwise the first expression. |
CASE | Evaluates conditions and returns the result for the first true condition. |
COALESCE() | Returns the first non-NULL value in the list. |
GREATEST() | Returns the largest value from a list of arguments. |
LEAST() | Returns the smallest value from a list of arguments. |
ELT() | Returns the element at the specified index in a list. |
FIELD() | Returns the index of a value in a list, or 0 if not found. |
ISNULL() | Checks if a value is NULL and returns 1 if true, 0 if false. |