Treat a MySQL column field as NULL if it is blank?


Let us first create a table −

mysql> create table DemoTable1362
    -> (
    -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> ClientName varchar(40)
    -> );
Query OK, 0 rows affected (0.67 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1362(ClientName) values('Chris');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1362(ClientName) values(' ');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable1362(ClientName) values('Bob');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1362(ClientName) values(' ');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1362(ClientName) values('David');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1362(ClientName) values(NULL);
Query OK, 1 row affected (0.07 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1362;

This will produce the following output −

+----------+------------+
| ClientId | ClientName |
+----------+------------+
|        1 | Chris      |
|        2 |            |
|        3 | Bob        |
|        4 |            |
|        5 | David      |
|        6 | NULL       |
+----------+------------+
6 rows in set (0.00 sec)

Following is the query to treat a column field as null if it is blank −

mysql> update DemoTable1362
    -> set ClientName=NULL
    -> where ClientName='' or length(ClientName)=0;
Query OK, 2 rows affected (0.21 sec)
Rows matched: 2  Changed: 2 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1362;

This will produce the following output −

+----------+------------+
| ClientId | ClientName |
+----------+------------+
|        1 | Chris      |
|        2 | NULL       |
|        3 | Bob        |
|        4 | NULL       |
|        5 | David      |
|        6 | NULL       |
+----------+------------+
6 rows in set (0.00 sec)

Updated on: 08-Nov-2019

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements