Yes, SELECT with an IF/ELSE is possible in MySQL.
Let us first create a table −
mysql> create table DemoTable721 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100), Marks int, CountryName varchar(100) ); Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable721(FirstName,Marks,CountryName) values('Chris',56,'US'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable721(FirstName,Marks,CountryName) values('Robert',78,'UK'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable721(FirstName,Marks,CountryName) values('Mike',45,'AUS'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable721(FirstName,Marks,CountryName) values('Carol',89,'ENG'); Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable721;
This will produce the following output -
+----+-----------+-------+-------------+ | Id | FirstName | Marks | CountryName | +----+-----------+-------+-------------+ | 1 | Chris | 56 | US | | 2 | Robert | 78 | UK | | 3 | Mike | 45 | AUS | | 4 | Carol | 89 | ENG | +----+-----------+-------+-------------+ 4 rows in set (0.00 sec)
Following is the query to implement SELECT with an IF/ELSE statement in MySQL −
mysql> select FirstName,IF(Marks > 75,Marks,CountryName) from DemoTable721;
This will produce the following output -
+-----------+----------------------------------+ | FirstName | IF(Marks > 75,Marks,CountryName) | +-----------+----------------------------------+ | Chris | US | | Robert | 78 | | Mike | AUS | | Carol | 89 | +-----------+----------------------------------+ 4 rows in set (0.00 sec)