How to use a single MySQL query to count column values ignoring null?


For this, you can COUNT() method, which does not include NULL value. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Name varchar(100),
   -> CountryName varchar(100)
   -> );
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John',null);
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('Chris','US');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values('Robert',null);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('Bob','UK');
Query OK, 1 row affected (0.57 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+--------+-------------+
| Name   | CountryName |
+--------+-------------+
| John   | NULL        |
| Chris  | US          |
| Robert | NULL        |
| Bob    | UK          |
+--------+-------------+
4 rows in set (0.00 sec)

Here is the query to use COUNT() and ignore NULL −

mysql> select count(Name) AS TotalName,count(CountryName) AS CountryWhichIsNotNull from DemoTable;

Output

This will produce the following output −

+-----------+-----------------------+
| TotalName | CountryWhichIsNotNull |
+-----------+-----------------------+
| 4         | 2                     |
+-----------+-----------------------+
1 row in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

102 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements