- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use if/else condition in select in MySQL?
Let us first create a table −
mysql> create table DemoTable1966 ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserName varchar(20), PhotoLiked int ); Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1966(UserName,PhotoLiked) values('Chris',57); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1966(UserName,PhotoLiked) values('David',100); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1966(UserName,PhotoLiked) values('Mike',68); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1966(UserName,PhotoLiked) values('Sam',78); Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1966;
This will produce the following output −
+--------+----------+------------+ | UserId | UserName | PhotoLiked | +--------+----------+------------+ | 1 | Chris | 57 | | 2 | David | 100 | | 3 | Mike | 68 | | 4 | Sam | 78 | +--------+----------+------------+ 4 rows in set (0.00 sec)
Here is the query to use if/else condition in SELECT with MySQL −
mysql> select if(PhotoLiked > 75,UserName,'Likes are less') as Result from DemoTable1966;
This will produce the following output −
+------------------------------------------------+ | Result | +------------------------------------------------+ | Likes are less | | David | | Likes are less | | Sam | +------------------------------------------------+ 4 rows in set (0.00 sec)
Advertisements