How to implement ternary conditional operator in MySQL?

MySQLMySQLi Database

A ternary conditional operator looks like ?: in programming language like C, C++, Java etc. The syntax is as follows −

(yourCondition) ? statement1:statement2;

In the above syntax, if yourCondition becomes true then statement1 will evaluate and if yourCondition becomes false then statement2 will evaluate.

But the above syntax does not work in MySQL. We can use IF() function from MySQL for the same purpose.

Let us see an example −

Case 1

mysql> select if(3 > 5,'Condition is true','Condition is not true') as ConditionalResult;

The following is the output in which second statement evaluates since is 3 isn’t more than 5 −

+-----------------------+
| ConditionalResult     |
+-----------------------+
| Condition is not true |
+-----------------------+
1 row in set (0.00 sec)

Case 2

mysql> select if(3 < 5,'Condition is true','Condition is not true') as ConditionalResult;

The following is the output in which the first statement evaluates since 3 is less than 5 −

+-------------------+
| ConditionalResult |
+-------------------+
| Condition is true |
+-------------------+
1 row in set (0.00 sec)
raja
Updated on 30-Jul-2019 22:30:24

Advertisements