To update a field if it is null, use IS NULL property along with the UPDATE command. Let us first create a table −
mysql> create table DemoTable ( StudentScore int ); Query OK, 0 rows affected (0.47 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(89); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(45); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(NULL); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(56); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+ | StudentScore | +--------------+ | 89 | | NULL | | 45 | | NULL | | 56 | +--------------+ 5 rows in set (0.00 sec)
Following is the query to update a field if it is null in MySQL −
mysql> update DemoTable set StudentScore=30 where StudentScore IS NULL; Query OK, 2 rows affected (0.34 sec) Rows matched: 2 Changed: 2 Warnings: 0
Let us check the table records once again.
mysql> select *from DemoTable;
This will produce the following output −
+--------------+ | StudentScore | +--------------+ | 89 | | 30 | | 45 | | 30 | | 56 | +--------------+ 5 rows in set (0.00 sec)