Web Info and IT Lessons Blog...

Tuesday, 16 December 2014

MySql IF Statement

The previous lesson of MySql Lessons Series was about MySql CONCAT Function and in this lesson we will learn about MySql IF Statement.

MySql IF Statement

MySql IF() is a conditional operation performed in a MySql query whenever WHERE condition is not enough to carry out an operation. The basic structure of MySql if statement is given below:


SELECT ColumnName(s), IF(Condition,True,False) FROM TableName 
WHERE 1

The IF statement in the above query has three parts:

1. Conditional Part
2. True Part
3. False Part

During the execution of IF statement, first of all the condition is checked. If condition is true the operation in the true part of IF statement is executed and vice versa. For a better understanding of MySql IF statement consider the table shown in the image below:

MySql IF Table

The above (user) table shows details of users and products bought by them. Let us create a scenario where MySql IF statement would be required to carry out the operation. If we want to fetch the names of users, the names of products bought and price of the products, it can be simply achieved by using a select query without any complications but what if we want to append currency to the price of the product using concatenation. Then in that case, we will have to append dollar for the users from 'America' and pound for the users from 'England'. The above scenario can be achieved by the query given below:


SELECT Name, Product_Name, 
IF(Country = 'England',CONCAT('£',Price),CONCAT('$',Price)) 
As Price FROM user

In the above query the condition is that if country of the user is England, pound sign is concatenated to the price of the product and if country of user is not England, dollar sign is concatenated to the product price. The output of the above query is shown in the image below:

MySql IF Result

Related Posts
CASE in MySQl
MySql FIND_IN_SET and MySql Locate
MySql Replace Function
MySql CONCAT() Function

No comments:

Post a Comment