Perform mathematical calculations in a MySQL table with NULL and NON-NULL values

MySQLMySQLi Database

For this, you can use IFNULL() and perform mathematical calculations with NULL and NON-NULL values. Let us first create a table −

mysql> create table DemoTable1462
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1462 values(10,20);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1462 values(50,NULL);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1462 values(NULL,70);
Query OK, 1 row affected (0.25 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1462;

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 |     20 |
|     50 |   NULL |
|   NULL |     70 |
+--------+--------+
3 rows in set (0.00 sec)

Following is the query to perform mathematical calculations in a MySQL table with NULL and NON-NULL values −

mysql> select ifnull(Value1,0)+ifnull(Value2,0) from DemoTable1462;

This will produce the following output −

+-----------------------------------+
| ifnull(Value1,0)+ifnull(Value2,0) |
+-----------------------------------+
|                                30 |
|                                50 |
|                                70 |
+-----------------------------------+
3 rows in set (0.00 sec)
raja
Published on 10-Dec-2019 06:57:35
Advertisements