Ignore NULL values from separate tables in a single MySQL query and display count of NOT NULL records

MySQLMySQLi Database

Let us first create a −

mysql> create table DemoTable1
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (1.06 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1 values(1);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1 values(NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1 values(2);
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable1 values(3);
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select −

mysql> select * from DemoTable1;

This will produce the following output −

+------+
| Id   |
+------+
|    1 |
| NULL |
|    2 |
|    3 |
+------+
4 rows in set (0.00 sec)

Following is the query to create second −

mysql> create table DemoTable2
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (0.65 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable2 values(10);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable2 values(NULL);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable2 values(NULL);
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select −

mysql> select * from DemoTable2;

This will produce the following output −

+------+
| Id   |
+------+
|   10 |
| NULL |
| NULL |
+------+
3 rows in set (0.00 sec)

Here is the query to ignore NULL values from separate tables−

mysql> select
   -> (
   -> select count(Id) from DemoTable1) as CountFirstTableId,
   -> (
   -> select count(Id) from DemoTable2) as CountSecondTableId
   -> ;

This will produce the following output −

+-------------------+--------------------+
| CountFirstTableId | CountSecondTableId |
+-------------------+--------------------+
|                 3 |                  1 |
+-------------------+--------------------+
1 row in set (0.00 sec)
raja
Published on 11-Nov-2019 10:36:26
Advertisements