MySQL: selecting rows where a column is null?

MySQLMySQLi Database

To select rows where a column is null, you can use IS NULL from MySQL with the help of where clause.

The syntax is as follows −

select *from yourTableName where yourColumnName IS NULL;

Let us first create a table to understand the concept −

mysql> create table NULLDemo1
   -> (
   -> StudentId int,
   -> StudentName varchar(100)
   -> );
Query OK, 0 rows affected (1.48 sec)

Inserting records into the table. The query to insert records is as follows −

mysql> insert into NULLDemo1 values(NULL,'John');
Query OK, 1 row affected (0.25 sec)
mysql> insert into NULLDemo1 values(100,'Johnson');
Query OK, 1 row affected (0.38 sec)
mysql> insert into NULLDemo1 values(NULL,'Carol');
Query OK, 1 row affected (0.25 sec)
mysql> insert into NULLDemo1 values(101,'Sam');
Query OK, 1 row affected (0.25 sec)

Now you can display all the records with the help of select statement. The query is as follows −

mysql> select *from NULLDemo1;

The following is the output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| NULL      | John        |
| 100       | Johnson     |
| NULL      | Carol       |  
| 101       | Sam         |   
+-----------+-------------+
4 rows in set (0.00 sec)

Apply the above syntax which was discussed in the beginning to select row where column is NULL. The query is as follows for the above table.

mysql> select *from NULLDemo1 where StudentId IS NULL;

Here is the output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| NULL      | John        |
| NULL      | Carol       |
+-----------+-------------+
2 rows in set (0.00 sec)
raja
Published on 21-Dec-2018 12:29:28
Advertisements