
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Ternary Conditional Operator in MySQL
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)
Advertisements