Sometimes you need to know the size of each mysql table to optimize them and gain some free space in the disk.
To do so, you can check manually the size of each table in the mysql datadir (generally it is /var/lib/mysql), or you can do even better by asking Mysql to do it for you.
Listing Mysql tables size
You can use the command below when connected to the mysql shell:
SELECT table_schema AS DB_NAME, TABLE_NAME, (DATA_LENGTH+INDEX_LENGTH)/1024 AS TABLE_SIZE_in_KB FROM information_schema.TABLES;
To list above tables size in MB:
SELECT table_schema AS DB_NAME, TABLE_NAME, (DATA_LENGTH+INDEX_LENGTH)/1024/1024 AS TABLE_SIZE_in_MB FROM information_schema.TABLES;
In this blog, I am using KB as the unit because I have small tables. So depending on the size of your data you can adjust the unit.
To list all tables having size bigger than 1 KB
SELECT table_schema AS DB_NAME, TABLE_NAME, (DATA_LENGTH+INDEX_LENGTH)/1024 AS TABLE_SIZE_in_KB FROM information_schema.TABLES WHERE (DATA_LENGTH+INDEX_LENGTH)/1024 > 1;
Example:
mysql> SELECT table_schema AS DB_NAME, TABLE_NAME, (DATA_LENGTH+INDEX_LENGTH)/1024 AS TABLE_SIZE_in_KB FROM information_schema.TABLES WHERE (DATA_LENGTH+INDEX_LENGTH)/1024 > 1;
Listing databases size
To list each database size you can use the following command:
SELECT table_schema "DATABASE_NAME", SUM(data_length + index_length) / 1024 "DATABASE SIZE IN KB" FROM information_schema.tables GROUP BY table_schema;
Example:
mysql> SELECT table_schema "DATABASE_NAME", SUM(data_length + index_length) / 1024 "DATABASE SIZE IN KB" FROM information_schema.tables GROUP BY table_schema;
Or in MB:
mysql> SELECT table_schema "DATABASE_NAME", SUM(data_length + index_length) / 1024 / 1024 "DATABASE SIZE IN MB" FROM information_schema.tables GROUP BY table_schema;
I hope that this blog helped you. Please visit our website for other interesting blogs and feel free to leave your feedbacks and thoughts. Till next time!
Latest posts by ZIADI Mohamed Ali (see all)
- How to show mounted devices in Linux? - July 25, 2017
- How to use Positional parameters and special variables in Linux - June 28, 2017
- Linux: Connect to your WiFi network through CLI? - June 25, 2017
- How to find a file in Linux? - March 19, 2017
- Mysql: How to find table and database size? - January 9, 2017