
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements