Set value only for NULL values in a MySQL table

MySQLMySQLi Database

Use IFNULL to check for NULL values and set a value using the SET command. Let us first create a table −

mysql> create table DemoTable817(Value int);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable817 values(10);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable817 values(null);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable817 values(20);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable817 values(null);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable817;

This will produce the following output −

+-------+
| Value |
+-------+
| 10    |
| NULL  |
| 20    |
| NULL  |
+-------+
4 rows in set (0.00 sec)

Following is the query to set value only for NULL values −

mysql> update DemoTable817 set Value=IFNULL(Value,0);
Query OK, 2 rows affected (0.17 sec)
Rows matched: 4 Changed: 2 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable817;

This will produce the following output −

+-------+
| Value |
+-------+
| 10    |
| 0     |
| 20    |
| 0     |
+-------+
4 rows in set (0.00 sec)
raja
Published on 03-Sep-2019 11:38:27
Advertisements