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: 2019-12-13T11:18:29+05:30

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements