
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
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)
Advertisements