Update all the fields in a table with null or non-null values with MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10,NULL);
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable values(NULL,'David');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(NULL,NULL);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output−

+------+-------+
|   Id | Name  |
+------+-------+
|   10 | NULL  |
| NULL | David |
| NULL | NULL  |
+------+-------+
3 rows in set (0.00 sec)

Here is the query to update all the fields in a table with null or non-null values −

mysql> update DemoTable set Name='Robert' where Id IS NULL or Name IS NULL;
Query OK, 3 rows affected (0.22 sec)
Rows matched: 3 Changed: 3 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable;

This will produce the following output −

+------+--------+
|   Id | Name   |
+------+--------+
|   10 | Robert |
| NULL | Robert |
| NULL | Robert |
+------+--------+
3 rows in set (0.00 sec)
raja
Published on 18-Dec-2019 06:10:57
Advertisements