How does MySQL IF() function work?


MySQL IF() function is one of the MySQL control flow functions that returns a value based on a condition. It is sometimes referred to as IF ELSE or IF THEN ELSE function. Basically, it takes three expressions and if the first expression is true (not ZERO and not NULL), it returns the second expression. Otherwise, it returns the third expression. Its syntax is as follows −

Syntax

IF(expr, value_if_true, value_if_false)

Here 

  • expr is the expression having some condition.
  • Value_if_true is the value to return if expr evaluates to TRUE.
  • Value_if_false is the value to return if expr evaluates to FALSE.

Example

mysql> Select IF(100=100,'YES','NO');
+------------------------+
| IF(100=100,'YES','NO') |
+------------------------+
| YES                    |
+------------------------+
1 row in set (0.00 sec)

mysql> Select IF(100=200,'YES','NO');
+------------------------+
| IF(100=200,'YES','NO') |
+------------------------+
| NO                     |
+------------------------+
1 row in set (0.00 sec)

Updated on: 20-Jun-2020

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements