Multiplying column with NULL row in MySQL?

MySQLMySQLi Database

To multiply with NULL row, you can use COALESCE(). Let us first create a table −

mysql> create table DemoTable1842
     (
     NumberOfItems int,
     Amount int
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1842 values(10,40);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1842 values(20,5);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1842 values(NULL,10);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1842;

This will produce the following output −

+---------------+--------+
| NumberOfItems | Amount |
+---------------+--------+
|            10 |     40 |
|            20 |      5 |
|          NULL |     10 |
+---------------+--------+
3 rows in set (0.00 sec)

Here is the query to multiply column with NULL rows −

mysql> select NumberOfItems,Amount,
     coalesce(NumberOfItems,1)*Amount as Total
     from DemoTable1842;

This will produce the following output −

+---------------+--------+-------+
| NumberOfItems | Amount | Total |
+---------------+--------+-------+
|            10 |     40 |   400 |
|            20 |      5 |   100 |
|          NULL |     10 |    10 |
+---------------+--------+-------+
3 rows in set (0.00 sec)
raja
Published on 26-Dec-2019 06:04:14
Advertisements