How to treat NULL as 0 and add columns in MySQL?


Use the concept of IFNULL() method to treat NULL as 0. 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.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Value1,Value2) values(10,20);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(Value1,Value2) values(null,null);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Value1,Value2) values(40,null);
Query OK, 1 row affected (0.18 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+--------+--------+
| Id | Value1 | Value2 |
+----+--------+--------+
| 1  | 10     | 20     |
| 2  | NULL   | NULL   |
| 3  | 40     | NULL   |
+----+--------+--------+
3 rows in set (0.00 sec)

Following is the query to treat NULL as 0 and add columns −

mysql> select ifnull(Value1,0)+ifnull(Value2,0) AS NULL_AS_ZERO from DemoTable;

This will produce the following output displaying the sum since all the NULL values were considered 0 for addition −

+--------------+
| NULL_AS_ZERO |
+--------------+
| 30           |
| 0            |
| 40           |
+--------------+
3 rows in set (0.00 sec)

Updated on: 30-Jul-2019

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements