How to count null values in MySQL?

MySQLMySQLi Database

To count null values in MySQL, you can use CASE statement. Let us first see an example and create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(20)
);
Query OK, 0 rows affected (0.77 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(FirstName) values(null);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable(FirstName) values('');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(FirstName) values('');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(FirstName) values(null);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values(null);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(FirstName) values('Bob');
Query OK, 1 row affected (0.15 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
| 1  | John      |
| 2  | NULL      |
| 3  |           |
| 4  | Larry     |
| 5  |           |
| 6  | NULL      |
| 7  | NULL      |
| 8  | Bob       |
+----+-----------+
8 rows in set (0.00 sec)

Here is the query to count Null values in MySQL −

mysql> select sum(case when FirstName IS NULL then 1 else 0 end) as NUMBER_OF_NULL_VALUE from DemoTable;

This will produce the following output −

+----------------------+
| NUMBER_OF_NULL_VALUE |
+----------------------+
| 3                    |
+----------------------+
1 row in set (0.00 sec)
raja
Published on 29-Apr-2019 09:21:36
Advertisements