How can I use MySQL IF() function within SELECT statement?


It is quite possible to use MySQL IF() function within SELECT statement by providing the name of the column along with a condition as the first argument of IF() function. To understand it, consider the following data from table ‘Students’.

mysql> Select * from Students;
+----+-----------+-----------+----------+----------------+
| id | Name      | Country   | Language | Course         |
+----+-----------+-----------+----------+----------------+
| 1  | Francis   | UK        | English  | Literature     |
| 2  | Rick      | USA       | English  | History        |
| 3  | Correy    | USA       | English  | Computers      |
| 4  | Shane     | France    | French   | Computers      |
| 5  | Validimir | Russia    | Russian  | Computers      |
| 6  | Steve     | Australia | English  | Geoinformatics |
| 7  | Rahul     | India     | Hindi    | Yoga           |
| 8 | Harshit | India | Hindi | Computers |
+----+-----------+-----------+----------+----------------+
8 rows in set (0.00 sec)

Now, with the help of the following query, having IF() function within SELECT statement, we are going to get the names and course details of the Students and if they have the English Language then it writes ‘Eng_Language’ otherwise ‘Other language’.

mysql> Select Name, IF(Language = 'English', "Eng_Language", "Other Language") AS 'Native Language', Course from students;
+-----------+-----------------+----------------+
| Name      | Native Language | Course         |
+-----------+-----------------+----------------+
| Francis   | Eng_Language    | Literature     |
| Rick      | Eng_Language    | History        |
| Correy    | Eng_Language    | Computers      |
| Shane     | Other Language  | Computers      |
| Validimir | Other Language  | Computers      |
| Steve     | Eng_Language    | Geoinformatics |
| Rahul     | Other Language  | Yoga           |
| Harshit   | Other Language  | Computers      |
+-----------+-----------------+----------------+
8 rows in set (0.00 sec)
Monica Mona
Monica Mona

Student of life, and a lifelong learner


Advertisements