How to use If-Else in Mysql

If else is basically used in the programming paradigm. We can use the same in Mysql.

How to use If-Else Mysql

Sometime it is very useful in programming. Suppose you have two column in the table as price and discountprice in the product column. You want to fetch the price and show it in the front end. If the discount is set in the table then it will be the actual price not the value that is set in the price column.

Lets take a record in the table,

Name Price discountprice
ABC 2300 2100
XYZ 2900

I want to show the discountprice as price if its value is there on the column as in the case of “ABC”
but the discountprice don’t have any value for the product XYZ .
Through programming we can check the discountprice and price column and will show the price according to it.
In PHP we can write the above as

$sql=mysql_query(“SELECT * FROM product”);

while($record=mysql_fetch_assoc($sql)){
if($record[‘discountprice ‘])
echo “Price : “.$record[‘discountprice ‘];
else
echo “Price :”.$record[‘price ‘];
}

Instead of applying logic in server side language like PHP, we can apply the login at query which is very correct approach also. the query will be like this.
SELECT IF(discountprice

From above query price will always have the minimium price out of the price and discountprice.

Read More Post