Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Count Null Values in MySQL



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)
Updated on: 2019-07-30T22:30:25+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements