You can use the COALESCE() function to convert MySQL null to 0
SELECT COALESCE(yourColumnName,0) AS anyAliasName FROM yourTableName;
Let us first create a table. The query to create a table is as follows
mysql> create table convertNullToZeroDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20), -> Salary int -> ); Query OK, 0 rows affected (1.28 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into convertNullToZeroDemo(Name,Salary) values('John',NULL); Query OK, 1 row affected (0.20 sec) mysql> insert into convertNullToZeroDemo(Name,Salary) values('Carol',5610); Query OK, 1 row affected (0.10 sec) mysql> insert into convertNullToZeroDemo(Name,Salary) values('Bob',NULL); Query OK, 1 row affected (0.15 sec) mysql> insert into convertNullToZeroDemo(Name,Salary) values('David',NULL); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from convertNullToZeroDemo;
The following is the output
+----+-------+--------+ | Id | Name | Salary | +----+-------+--------+ | 1 | John | NULL | | 2 | Carol | 5610 | | 3 | Bob | NULL | | 4 | David | NULL | +----+-------+--------+ 4 rows in set (0.05 sec)
Here is the query to convert MySQL NULL to 0 using COALESCE() function
mysql> select coalesce(Salary,0) as `CONVERT_NULL _TO_0` from convertNullToZeroDemo;
The following is the output
+--------------------+ | CONVERT_NULL _TO_0 | +--------------------+ | 0 | | 5610 | | 0 | | 0 | +--------------------+ 4 rows in set (0.00 sec)