MySQL query to convert empty values to NULL?

MySQLMySQLi Database

It’s easy to convert empty values to NULL using SET and WHERE. Let us first create a table −

mysql> create table DemoTable1315
-> (
-> CountryName varchar(10)
-> );
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command. We have set some empty values here as well −

mysql> insert into DemoTable1315 values('US');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1315 values('');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1315 values('UK');
Query OK, 1 row affected (0.70 sec)
mysql> insert into DemoTable1315 values('');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1315 values('');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1315 values('AUS');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable1315;

Output

+-------------+
| CountryName |
+-------------+
| US          |
|             |
| UK          |
|             |
|             |
| AUS         |
+-------------+
6 rows in set (0.00 sec)

Here is the query to convert empty values to NULL −

mysql> update DemoTable1315 set CountryName=NULL where CountryName='';
Query OK, 3 rows affected (0.16 sec)
Rows matched: 3 Changed: 3 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable1315;

Output

+-------------+
| CountryName |
+-------------+
| US          |
| NULL        |
| UK          |
| NULL        |
| NULL        |
| AUS         |
+-------------+
6 rows in set (0.00 sec)
raja
Published on 04-Nov-2019 10:54:08
Advertisements