Count(*) rows from multiple tables in MySQL?


To count rows from multiple tables in MySQL, the syntax is as follows −

Select
    (select count(*) from yourTableName1) as anyAliasName1,
    (select count(*) from yourTableName2) as anyAliasName2
    from dual;

Let us first create a table −

mysql> create table DemoTable1
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY
   -> );
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1 values(),(),(),(),(),();
Query OK, 6 rows affected (0.24 sec)
Records: 6  Duplicates: 0  Warnings: 0

Display all records from the table using select statement −

mysql> select * from DemoTable1;

This will produce the following output −

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

Following is the query to create second table −

mysql> create table DemoTable2
    -> (
    -> Name varchar(20)
    -> );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2 values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable2 values('David');
Query OK, 1 row affected (0.31 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable2;

This will produce the following output −

+-------+
| Name  |
+-------+
| Chris |
| David |
+-------+
2 rows in set (0.00 sec)

Following is the query to count rows from multiple tables −

mysql> select
   -> (select count(*) from DemoTable1) as FirstTable1Count,
   -> (select count(*) from DemoTable2) as SecondTable2Count
   -> from dual;

This will produce the following output −

+---------------------+----------------------+
| FirstTable1Count    |    SecondTable2Count |
+---------------------+----------------------+
|                   6 |                    2 |
+---------------------+----------------------+
1 row in set (0.00 sec)

Updated on: 12-Dec-2019

885 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements