Counting the number of non-null or nonzero columns in a MySQL table?

MySQLMySQLi Database

Use if() method for this. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Number1 int,
   -> Number2 int
   -> );
Query OK, 0 rows affected (1.15 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Number1,Number2) values(10,20);
Query OK, 1 row affected (0.41 sec)

mysql> insert into DemoTable(Number1,Number2) values(0,32);
Query OK, 1 row affected (0.38 sec)

mysql> insert into DemoTable(Number1,Number2) values(40,0);
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(Number1,Number2) values(40,50);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+----+---------+---------+
| Id | Number1 | Number2 |
+----+---------+---------+
| 1  | 10      | 20      |
| 2  | 0       | 32      |
| 3  | 40      | 0       |
| 4  | 40      | 50      |
+----+---------+---------+
4 rows in set (0.00 sec)

Following is the query to count the number of non-null or non-zero columns in a table −

mysql> select *,
-> if(Number1 <> 0,1,0)+if(Number2 <> 0,1,0) AS TotalCount
-> from DemoTable;

Output

This will produce the following output −

+----+---------+---------+------------+
| Id | Number1 | Number2 | TotalCount |
+----+---------+---------+------------+
| 1  | 10      | 20      | 2          |
| 2  | 0       | 32      | 1          |
| 3  | 40      | 0       | 1          |
| 4  | 40      | 50      | 2          |
+----+---------+---------+------------+
4 rows in set (0.00 sec)
raja
Published on 09-Jul-2019 14:32:40
Advertisements