Set conditions while adding column values in MySQL?

MySQLMySQLi Database

To set conditions while adding column values, use MySQL IF(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int,
   -> Value3 int
   -> );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10,20,-30);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(50,60,90);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(100,200,400);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(30,40,-50);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(70,80,-1);
Query OK, 1 row affected (0.24 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+--------+--------+--------+
| Value1 | Value2 | Value3 |
+--------+--------+--------+
|     10 |     20 |    -30 |
|     50 |     60 |     90 |
|    100 |    200 |    400 |
|     30 |     40 |    -50 |
|     70 |     80 |     -1 |
+--------+--------+--------+
5 rows in set (0.00 sec)

Here is the query to set conditions while adding column values −

mysql> select Value1+Value2+if(Value3 > 0,Value3,0) from DemoTable;

This will produce the following output −

+---------------------------------------+
| Value1+Value2+if(Value3 > 0,Value3,0) |
+---------------------------------------+
|                                    30 |
|                                   200 |
|                                   700 |
|                                    70 |
|                                   150 |
+---------------------------------------+
5 rows in set (0.00 sec)
raja
Published on 18-Dec-2019 05:59:33
Advertisements