Finding total number of rows of tables across multiple databases in MySQL?


To fetch total number of table rows across databases, use aggregate function SUM() along with INFORMATION SCHEMA. Let us first create a table, which is in “web” database −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable1568 values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1568 values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1568 values('David');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1568;

This will produce the following output −

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

Following is the query to create a table in the database “sample” −

mysql> use sample;
Database changed
mysql> create table DemoTable1568
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (0.99 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1568 values(101);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1568 values(102);
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable1568 values(103);
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable1568 values(104);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1568;

This will produce the following output −

+------+
| Id   |
+------+
|  101 |
|  102 |
|  103 |
|  104 |
+------+
4 rows in set (0.00 sec)

Here is the query to find total number of rows of tables across multiple databases −

mysql> select sum(table_rows) as TotalNumberOfRows from information_schema.tables
   -> where table_name='DemoTable1568';

This will produce the following output −

+-------------------+
| TotalNumberOfRows |
+-------------------+
|                 7 |
+-------------------+
1 row in set (0.19 sec)

Updated on: 13-Dec-2019

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements