
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
If-Else Statement in MySQL
In an If-Else statement, the condition is evaluated to be true or false depending on the value.
Let us see an example. Firstly, we will create a table. The CREATE command is used to create a table.
mysql> create table IfelseDemo - > ( - > id int, - > FirstName varchar(100) - > ); Query OK, 0 rows affected (0.46 sec)
Records are inserted with the help of INSERT command.
mysql> insert into IfelseDemo values(1,'John'); Query OK, 1 row affected (0.13 sec) mysql> insert into IfelseDemo values(2,'Carol'); Query OK, 1 row affected (0.31 sec) mysql> insert into IfelseDemo values(3,'John'); Query OK, 1 row affected (0.11 sec) mysql> insert into IfelseDemo values(4,'Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into IfelseDemo values(5,'John'); Query OK, 1 row affected (0.11 sec)
Displaying all records.
mysql> select *from IfelseDemo;
Here is our output.
+------+-----------+ | id | FirstName | +------+-----------+ | 1 | John | | 2 | Carol | | 3 | John | | 4 | Carol | | 5 | John | +------+-----------+ 5 rows in set (0.00 sec)
The following is the query for using the if-else statement.
mysql> SELECT id, FirstName, (case when (id = 2 and FirstName = 'Carol') - > then - > 'Welcome Carol' - > else - > 'You are not Carol with id 2' - >end)as Message from IfelseDemo;
The following is the output.
+------+-----------+-----------------------------+ | id | FirstName | Message | +------+-----------+-----------------------------+ | 1 | John | You are not Carol with id 2 | | 2 | Carol | Welcome Carol | | 3 | John | You are not Carol with id 2 | | 4 | Carol | You are not Carol with id 2 | | 5 | john | You are not Carol with id 2 | +------+-----------+-----------------------------+ 5 rows in set (0.00 sec)
Advertisements