Check whether a field is empty or null in MySQL?


NULL and empty string ‘ ’ both aren’t similar in MySQL. To check the field is empty like ‘ ’or is null, you need to use the IS NULL property or something else. You can check all the conditions with CASE statement. The syntax is as follows:

SELECT *, CASE
WHEN yourColumnName =’ ‘ THEN ‘yourMessage1’
WHEN yourColumnName IS NULL THEN ‘yourMessage2’
ELSE CONCAT(yourColumnName ,' is a Name')
END AS anyVariableName
FROM yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows:

mysql> create table checkFieldDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(10),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command. The query is as follows:

mysql> insert into checkFieldDemo(Name) values(NULL);
Query OK, 1 row affected (0.17 sec)
mysql> insert into checkFieldDemo(Name) values('John');
Query OK, 1 row affected (0.15 sec)
mysql> insert into checkFieldDemo(Name) values(NULL);
Query OK, 1 row affected (0.10 sec)
mysql> insert into checkFieldDemo(Name) values('');
Query OK, 1 row affected (0.51 sec)
mysql> insert into checkFieldDemo(Name) values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into checkFieldDemo(Name) values('');
Query OK, 1 row affected (0.17 sec)
mysql> insert into checkFieldDemo(Name) values(NULL);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement. The query is as follows:

mysql> select *from checkFieldDemo;

The following is the output:

+----+-------+
| Id | Name  |
+----+-------+
|  1 | NULL  |
|  2 | John  |
|  3 | NULL  |
|  4 |       |
|  5 | Carol |
|  6 |       |
|  7 | NULL  |
+----+-------+
7 rows in set (0.00 sec)

Here is the query to check field is empty or null or something else using case statement. The query is as follows:

mysql> select *,case
   -> when Name='' then 'It is an empty string'
   -> when Name is null then 'It is a NULL value'
   -> else concat(Name,' is a Name')
   -> END as ListOfValues
   -> from checkFieldDemo;

The following is the output:

+----+-------+-----------------------+
| Id | Name  | ListOfValues          |
+----+-------+-----------------------+
|  1 | NULL  | It is a NULL value    |
|  2 | John  | John is a Name        |
|  3 | NULL  | It is a NULL value    |
|  4 |       | It is an empty string |
|  5 | Carol | Carol is a Name       |
|  6 |       | It is an empty string |
|  7 | NULL  | It is a NULL value    |
+----+-------+-----------------------+
7 rows in set (0.00 sec)

Updated on: 30-Jul-2019

616 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements