MySQL中查看表大小应使用information_schema.tables查询data_length+index_length,它反映数据与索引总占用空间(单位字节),再换算为MB;InnoDB行数为估算值,真实文件大小需结合ls -lh验证碎片情况。

在 MySQL 中查看表大小,主要是为了了解数据文件和索引文件实际占用的磁盘空间,尤其在排查磁盘告警、优化大表或评估归档需求时非常实用。注意:表大小 ≠ 表中数据行数 × 单行平均长度,它受存储引擎(InnoDB/MyISAM)、行格式、碎片、索引数量、空闲空间等多种因素影响。
查单个表的精确大小(含数据+索引)
推荐使用 information_schema.tables,这是最通用且准确的方式:
SELECT table_name AS `表名`, ROUND((data_length + index_length) / 1024 / 1024, 2) AS `大小(MB)`, ROUND(data_length / 1024 / 1024, 2) AS `数据(MB)`, ROUND(index_length / 1024 / 1024, 2) AS `索引(MB)`, table_rows AS `行数` FROM information_schema.tables WHERE table_schema = 'your_database_name' AND table_name = 'your_table_name';
-
data_length:主数据存储占用(如 InnoDB 的聚簇索引页、MyISAM 的 .MYD 文件) -
index_length:所有二级索引占用(.MYI 文件或 InnoDB 的辅助索引页) - 结果单位为字节,除以
1024²转为 MB 更直观 - 对 InnoDB 表,
table_rows是估算值(来自统计信息),不一定完全精确
查整个库的表大小排行(Top N 大表)
快速定位“磁盘大户”,便于优先优化:
SELECT table_name AS `表名`, ROUND((data_length + index_length) / 1024 / 1024, 2) AS `大小(MB)`, ROUND(data_length / 1024 / 1024, 2) AS `数据(MB)`, ROUND(index_length / 1024 / 1024, 2) AS `索引(MB)` FROM information_schema.tables WHERE table_schema = 'your_database_name' AND table_type = 'BASE TABLE' ORDER BY data_length + index_length DESC LIMIT 10;
- 加
AND table_type = 'BASE TABLE'排除视图(view)干扰 - 按
data_length + index_length降序,确保真正占空间的表排在前面 - 可把
LIMIT 10改成LIMIT 20或去掉,看全部
查 InnoDB 表的真实物理文件大小(验证是否碎片化)
information_schema 提供的是逻辑大小估算;若想确认磁盘上 .ibd 文件真实大小,需结合操作系统命令(适用于独立表空间 innodb_file_per_table=ON):
- 先查表对应 .ibd 文件名:
SELECT file_name FROM information_schema.innodb_datafiles WHERE file_name LIKE '%your_table_name%';
(或直接看SELECT table_name, engine, row_format FROM information_schema.tables...确认是 InnoDB + 独立表空间) - 登录服务器,进数据库数据目录(如
/var/lib/mysql/your_database_name/),执行:ls -lh your_table_name.ibd - 对比
ls -lh结果与information_schema中的data_length + index_length:
若磁盘文件明显更大(比如大 30% 以上),说明存在较多空闲页(碎片),可考虑OPTIMIZE TABLE your_table_name;(注意锁表风险)
补充说明:MyISAM 和 InnoDB 的差异要点
不同引擎计算逻辑一致,但底层含义不同:
-
MyISAM:
data_length≈ .MYD 文件大小,index_length≈ .MYI 文件大小,基本等于磁盘占用 -
InnoDB:
- 若
innodb_file_per_table=ON(默认),每张表有独立 .ibd 文件,data_length + index_length接近该文件大小 - 若
OFF,所有表共享 ibdata1,此时information_schema中的大小仍有效,但无法对应到单个文件 - InnoDB 表可能包含未 purge 的旧版本记录(MVCC),也会略微推高
data_length
- 若










