Computer >> Computer tutorials >  >> Programming >> MySQL

MySQL select query to fetch data with null value?


Let us first create a table −

mysql> create table DemoTable
(
   CustomerName varchar(100),
   CustomerCountryName varchar(100)
);
Query OK, 0 rows affected (0.95 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris','US');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Bob','UK');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Carol',NULL);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('David','AUS');
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable values('Mike',NULL);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------+---------------------+
| CustomerName | CustomerCountryName |
+--------------+---------------------+
| Chris        | US                  |
| Bob          | UK                  |
| Carol        | NULL                |
| David        | AUS                 |
| Mike         | NULL                |
+--------------+---------------------+
5 rows in set (0.00 sec)

Following is the query to fetch data with null value −

mysql> select *from DemoTable where CustomerCountryName IS NULL;

This will produce the following output −

+--------------+---------------------+
| CustomerName | CustomerCountryName |
+--------------+---------------------+
| Carol        | NULL                |
| Mike         | NULL                |
+--------------+---------------------+
2 rows in set (0.00 sec)