Skip to content

MySQL IF Function

In this tutorial, you will learn how to use MySQL IF function. MySQL IF function is one of the MySQL control flow functions that returns a value based on a condition. The IF function is sometimes referred to as IF ELSE or IF THEN ELSE function.

The IF function takes the following three arguments, the conditional, the “true” value and the “false” value. False and true values may be static values or column values.

Depending on the context in which it is used, it returns either numeric or string value.

The syntax of the MySQL IF function is as follows:

 IF(expr,if_true_expr,if_false_expr) 

MySql If function Examples –

mysql> SELECT IF(1>2,2,3);
        -> 3
mysql> SELECT IF(1<2,'yes','no');
        -> 'yes'
mysql> SELECT IF(STRCMP('test','test1'),'no','yes');
        -> 'no'

mysql> SELECT IF(role_id = 1,'admin','user') role FROM users WHERE user_id = 1;
        -> 'admin'

IF statements can also be nested,

mysql> SELECT IF(1>2,2,IF(3 > 4,4,5));
        -> 5
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments