How to use if/else condition in select in MySQL?

MySQLMySQLi Database

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)
raja
Published on 31-Dec-2019 07:35:56
Advertisements