You can use NULLIF() from MySQL to replace 0 with NULL. The syntax is as follows −
SELECT *,NULLIF(yourColumnName,0) as anyVariableName from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table Replace0WithNULLDemo -> ( -> Id int NOT NULL auto_increment, -> Name varchar(20), -> Marks int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.53 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into Replace0WithNULLDemo(Name,Marks) values('John',76); Query OK, 1 row affected (0.16 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Carol',86); Query OK, 1 row affected (0.20 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Sam',0); Query OK, 1 row affected (0.17 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Mike',0); Query OK, 1 row affected (0.16 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Larry',98); Query OK, 1 row affected (0.19 sec) mysql> insert into Replace0WithNULLDemo(Name,Marks) values('Bob',0); Query OK, 1 row affected (0.17 sec)
Display records from the table using select statement. The query is as follows −
mysql> select *from Replace0WithNULLDemo;
The following is the output −
+----+-------+-------+ | Id | Name | Marks | +----+-------+-------+ | 1 | John | 76 | | 2 | Carol | 86 | | 3 | Sam | 0 | | 4 | Mike | 0 | | 5 | Larry | 98 | | 6 | Bob | 0 | +----+-------+-------+ 6 rows in set (0.00 sec)
Let us now replace 0 with NULL. The query is as follows −
mysql> select *,NULLIF(Marks,0) as ReplaceZeroWithNULL from Replace0WithNULLDemo;
The following is the output displaying a new column wherein new have replaced 0 with NULL −
+----+-------+-------+---------------------+ | Id | Name | Marks | ReplaceZeroWithNULL | +----+-------+-------+---------------------+ | 1 | John | 76 | 76 | | 2 | Carol | 86 | 86 | | 3 | Sam | 0 | NULL | | 4 | Mike | 0 | NULL | | 5 | Larry | 98 | 98 | | 6 | Bob | 0 | NULL | +----+-------+-------+---------------------+ 6 rows in set (0.00 sec)