Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Add values of two columns considering NULL values as zero in MySQL
For this, use COALESCE() function from MySQL. Let us first create a table −
mysql> create table DemoTable -> ( -> Value1 int, -> Value2 int -> ); Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100,200); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values(NULL,90); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(NULL,NULL); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(600,NULL); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
This will produce the following output −
+--------+--------+ | Value1 | Value2 | +--------+--------+ | 100 | 200 | | NULL | 90 | | NULL | NULL | | 600 | NULL | +--------+--------+ 4 rows in set (0.00 sec)
Following is the query to treat NULL as zero and add values from two columns −
mysql> SELECT COALESCE(Value1, 0) + COALESCE(Value2, 0) AS Sum from DemoTable;
Output
This will produce the following output −
+------+ | Sum | +------+ | 300 | | 90 | | 0 | | 600 | +------+ 4 rows in set (0.00 sec)
Advertisements
