Syntax error How to skip blank and null values in MySQL?

How to skip blank and null values in MySQL?



To skip blank and null in MySQL, use the following syntax:

select *from yourTableName where yourColumnName IS NOT NULL AND yourColumnName <> '';

Let us first create a table:

mysql> create table DemoTable (Id int, FirstName varchar(20));
Query OK, 0 rows affected (0.66 sec)

Following is the query to insert records in the table using insert command:

mysql> insert into DemoTable values(100,'Larry');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(101,'');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(102,'Chris');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(103,null);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(104,' ');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(105,'Robert');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(106,null);
Query OK, 1 row affected (0.13 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output with blank values and NULL:

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Larry     |
| 101  |           |
| 102  | Chris     |
| 103  | NULL      |
| 104  |           |
| 105  | Robert    |
| 106  | NULL      |
+------+-----------+
7 rows in set (0.00 sec)

Following is the query to skip blank values as well as null in MySQL:

mysql> select *from DemoTable where FirstName IS NOT NULL AND FirstName <> '';

This will produce the following output

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Larry     |
| 102  | Chris     |
| 105  | Robert    |
+------+-----------+
3 rows in set (0.03 sec)
Updated on: 2019-07-30T22:30:25+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements