Perform multiplication in SELECT depending on column value in MySQL?


You can use CASE statement for this. Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Value1 int,
   Value2 int
   );
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Value1,Value2) values(10,5);
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable(Value1,Value2) values(20,0);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Value1,Value2) values(40,10);
Query OK, 1 row affected (0.28 sec)

mysql> insert into DemoTable(Value1,Value2) values(50,0);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+--------+
| Id | Value1 | Value2 |
+----+--------+--------+
|  1 | 10     | 5      |
|  2 | 20     | 0      |
|  3 | 40     | 10     |
|  4 | 50     | 0      |
+----+--------+--------+
4 rows in set (0.00 sec)

Following is the query to perform multiplication in SELECT depending on column value −

mysql> select Value1,Value2,
   case when Value2 > 0 then Value1*Value2 else 0 end as Multiplication from DemoTable;

This will produce the following output −

+--------+--------+----------------+
| Value1 | Value2 | Multiplication |
+--------+--------+----------------+
|     10 |      5 |             50 |
|     20 |      0 |              0 |
|     40 |     10 |            400 |
|     50 |      0 |              0 |
+--------+--------+----------------+
4 rows in set (0.00 sec)
raja
Published on 17-May-2019 17:23:31
Advertisements