For performing mathematical operations and working with conditions, you can consider CASE statement. Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FruitName varchar(100), FruitPrice int ); Query OK, 0 rows affected (0.26 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(FruitName,FruitPrice) values('Orange',250); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(FruitName,FruitPrice) values('Banana',100); Query OK, 1 row affected (0.05 sec) mysql> insert into DemoTable(FruitName,FruitPrice) values('Apple',150); Query OK, 1 row affected (0.05 sec) mysql> insert into DemoTable(FruitName,FruitPrice) values('Pomegranate',200); Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-------------+------------+ | Id | FruitName | FruitPrice | +----+-------------+------------+ | 1 | Orange | 250 | | 2 | Banana | 100 | | 3 | Apple | 150 | | 4 | Pomegranate | 200 | +----+-------------+------------+ 4 rows in set (0.19 sec)
Following is the query for CASE statement with mathematical operations −
mysql> select Id,FruitName,FruitPrice, case when FruitName='Orange' then FruitPrice/5 else FruitPrice end as OriginalPrice from DemoTable;
This will produce the following output −
+----+-------------+------------+---------------+ | Id | FruitName | FruitPrice | OriginalPrice | +----+-------------+------------+---------------+ | 1 | Orange | 250 | 50.0000 | | 2 | Banana | 100 | 100 | | 3 | Apple | 150 | 150 | | 4 | Pomegranate | 200 | 200 | +----+-------------+------------+---------------+ 4 rows in set (0.00 sec)