The IF Function - Conditional value selection in SQL queries |
|
| IF | Syntax: | IF(Expression, Value1, Value2) | Return value: | Depending on the data types used | Function type: | Comparison function | |
| | The IF() function returns "Value1" if "Expression" is TRUE, or "Value2" if the condition FALSE.
If the value of "Expression" is NULL, the condition is FALSE. | SQL Examples for the IF function |
|
select if(true, 'value true', 'value false');
select if(false, 'value true', 'value false');
select if(3 > 4, 'value true', 'value false');
select if(3 < 4, 'value true', 'value false');
select if(null, 'value true', 'value false');
select if(3 = 4, 'ok', null);
select if(3 <> 4, 'ok', null);
|
|
if(true, 'value true', 'value false') |
varchar(11) BINARY |
value true |
|
|
if(false, 'value true', 'value false') |
varchar(11) BINARY |
value false |
|
|
if(3 > 4, 'value true', 'value false') |
varchar(11) BINARY |
value false |
|
|
if(3 < 4, 'value true', 'value false') |
varchar(11) BINARY |
value true |
|
|
if(null, 'value true', 'value false') |
varchar(11) BINARY |
value false |
|
|
if(3 = 4, 'ok', null) |
varchar(2) BINARY |
NULL |
|
|
if(3 <> 4, 'ok', null) |
varchar(2) BINARY |
ok |
|
|
| The examples were created with the MyWAY SQL manager: | How to use the IF() function in MySQL and MariaDB databases | In both MySQL and MariaDB the IF() function is used to perform conditional logic within SQL querys and allows to return different values based on a specified condition. The function can also be used in combination with other functions or expressions, for example to adjust the returned values based on certain conditions.
The true and false expressions can be literals, table column values, or subqueries, but their data types should be compatible. The IF() function in MySQL and MariaDB provides a good way to get values based on specified conditions to return conditionally, which gives much more flexibility to SQL queries against databases. | | Further MySQL und MariaDB SQL Comparison functions | |
| | More information about the IF SQL function: and and |
|
|
|
|