You can typecast NULL to 0 with the help of IFNULL() function. The syntax is as follows −
select ifnull(yourColumnName) as anyVariableName from yourTableName;
To understand the above concept, let us first create a table −
mysql> create table TypecastDemo −> ( −> AccountNumber int −> ); Query OK, 0 rows affected (0.84 sec)
Let us insert some records with NULL value. The query to insert records is as follows −
mysql> insert into TypecastDemo values(NULL); Query OK, 1 row affected (0.13 sec) mysql> insert into TypecastDemo values(1234); Query OK, 1 row affected (0.14 sec) mysql> insert into TypecastDemo values(9876); Query OK, 1 row affected (0.14 sec) mysql> insert into TypecastDemo values(6666); Query OK, 1 row affected (0.16 sec) mysql> insert into TypecastDemo values(NULL); Query OK, 1 row affected (0.27 sec) mysql> insert into TypecastDemo values(NULL); Query OK, 1 row affected (0.36 sec) mysql> insert into TypecastDemo values(3214); Query OK, 1 row affected (0.34 sec)
Now you can display all the records with the help of select statement. The query is as follows −
mysql> select *from TypecastDemo;
The following is the output −
+---------------+ | AccountNumber | +---------------+ | NULL | | 1234 | | 9876 | | 6666 | | NULL | | NULL | | 3214 | +---------------+ 7 rows in set (0.00 sec)
Apply the syntax we saw above to typecast the NULL to 0. The query is as follows −
mysql> select ifnull(AccountNumber,0) as TypeCastNullToZero from TypecastDemo;
The following is the output −
+--------------------+ | TypeCastNullToZero | +--------------------+ | 0 | | 1234 | | 9876 | | 6666 | | 0 | | 0 | | 3214 | +--------------------+ 7 rows in set (0.00 sec)
Suppose you want more than one column then you can use COALESCE.