Как узнать размер базы и самых больших таблиц в MySQL 8.0
Диагностические SELECT-запросы к INFORMATION_SCHEMA для оценки размера баз, данных и индексов в MySQL 8.0 с объяснением ограничений InnoDB.

В этой статье
Размер каталога MySQL на диске и сумма таблиц в отчёте могут различаться. База использует журналы, временные файлы, системные таблицы и свободное место внутри табличных пространств. Поэтому запрос к INFORMATION_SCHEMA отвечает на конкретный вопрос: сколько данных и индексов движок учитывает для таблиц, а не сколько гигабайт занимает весь экземпляр сервера.
Руководство предназначено для MySQL 8.0. Запросы только читают метаданные и не изменяют таблицы. Проверено 25 сентября 2026 года по официальному справочнику MySQL 8.0. Живого экземпляра MySQL в изолированном окружении не было, поэтому синтаксис и поведение сверены с документацией, но фактический план и время выполнения на стенде не измерялись. Для крупного рабочего сервера запросы выполняйте в период умеренной нагрузки и под учётной записью с минимальными правами на нужные схемы.
Посмотрите размеры пользовательских баз
Запрос суммирует объём данных и индексов, исключая системные схемы. Результат округляется до мегабайт.
SELECT
table_schema AS database_name,
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb
FROM information_schema.tables
WHERE table_schema NOT IN (
'information_schema',
'mysql',
'performance_schema',
'sys'
)
GROUP BY table_schema
ORDER BY SUM(data_length + index_length) DESC;
Столбец data_length отражает данные, а index_length — индексы. Для InnoDB оба значения приблизительные: они основаны на выделенных страницах. Это нормально для планирования и поиска крупных объектов, но не является точным счётом полезных байтов.
Найдите самые большие таблицы выбранной базы
Замените заглушку YOUR_DATABASE на имя нужной схемы. Заглушку не оставляют в рабочем запросе и не подставляют вместе с кавычками из внешнего непроверенного ввода.
SELECT
table_name,
engine,
table_rows,
ROUND(data_length / 1024 / 1024, 2) AS data_mb,
ROUND(index_length / 1024 / 1024, 2) AS index_mb,
ROUND((data_length + index_length) / 1024 / 1024, 2) AS total_mb
FROM information_schema.tables
WHERE table_schema = 'YOUR_DATABASE'
AND table_type = 'BASE TABLE'
ORDER BY (data_length + index_length) DESC
LIMIT 20;
Условие table_type = 'BASE TABLE' исключает представления. Ограничение LIMIT 20 оставляет первые двадцать таблиц и не влияет на данные. Поле table_rows для InnoDB — приблизительная оценка и может заметно отличаться от точного количества строк.
Отделите данные от индексов
Большой индекс не обязательно лишний. Он может ускорять критичные запросы. Но таблица, где индексы значительно тяжелее данных, заслуживает отдельной проверки: какие индексы используются, нет ли повторяющихся составных ключей и как меняется запись.
SELECT
table_name,
ROUND(data_length / 1024 / 1024, 2) AS data_mb,
ROUND(index_length / 1024 / 1024, 2) AS index_mb,
ROUND(
index_length / NULLIF(data_length, 0),
2
) AS index_to_data_ratio
FROM information_schema.tables
WHERE table_schema = 'YOUR_DATABASE'
AND table_type = 'BASE TABLE'
ORDER BY index_length DESC
LIMIT 20;
Функция NULLIF защищает расчёт от деления на ноль. Коэффициент помогает сортировать кандидатов, но не доказывает избыточность индекса. Решение об удалении требует анализа запросов, ограничений уникальности и резервной копии; это уже отдельная работа, которой в руководстве нет.
Почему цифры могут быть не свежими
MySQL кэширует статистику таблиц. По умолчанию срок её действия может составлять 24 часа. Запрос к INFORMATION_SCHEMA способен показать прежнюю оценку после большой загрузки или удаления данных.
Команда ANALYZE TABLE обновляет статистику, но это уже операция изменения служебных данных и может влиять на нагрузку и планы запросов. Не запускайте её автоматически только ради красивого отчёта. Если нужны свежие оценки, согласуйте окно и последствия с администратором.
Что не входит в сумму таблиц
Бинарные журналы и relay log репликации.
Redo и undo, системное табличное пространство и служебные файлы InnoDB.
Временные таблицы и временные файлы запросов.
Резервные копии, дампы и журналы приложения рядом с каталогом базы.
Свободное место внутри общего табличного пространства, которое нельзя однозначно приписать одной таблице.
Поэтому для задачи «почему заканчивается диск» запрос дополняют проверкой файловой системы и конфигурации MySQL. Для задачи «какие таблицы растут» полезнее сохранять результаты одинакового запроса по датам и сравнивать прирост.
Критерий завершённой проверки
Зафиксирована версия MySQL и имя анализируемой схемы.
Получены размеры баз и первые двадцать таблиц.
Отдельно просмотрены данные и индексы, но выводы об удалении не сделаны по одному коэффициенту.
Отмечено время получения и возможная давность статистики.
Свободное место диска проверено отдельно от оценки таблиц.
Если рост неожиданный, определён владелец таблицы и период, за который нужно сравнить данные.
Диагностические SELECT-запросы безопаснее, чем попытка сразу уменьшать таблицу, но на большом экземпляре даже чтение метаданных может занять время. Если сервер уже перегружен или реплика отстаёт, остановитесь после минимального запроса и согласуйте продолжение с администратором базы.
The size of the MySQL directory on disk and the sum of tables in the report may differ. The database uses logs, temporary files, system tables, and free space within table spaces. Therefore, a query against INFORMATION_SCHEMA answers a specific question: how much data and indexes the engine counts for tables, not how many gigabytes the entire server instance occupies.
This guide is intended for MySQL 8.0. The queries only read metadata and do not modify tables. Verified on September 25, 2026, against the official MySQL 8.0 reference manual. There was no live MySQL instance in an isolated environment, so syntax and behavior were cross-checked with documentation, but the actual execution plan and runtime on the test stand were not measured. For a large production server, run these queries during moderate load and under an account with minimal privileges for the required schemas.
View user database sizes
The query sums data and index volumes, excluding system schemas. Results are rounded to megabytes.
SELECT
table_schema AS database_name,
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb
FROM information_schema.tables
WHERE table_schema NOT IN (
'information_schema',
'mysql',
'performance_schema',
'sys'
)
GROUP BY table_schema
ORDER BY SUM(data_length + index_length) DESC;
The column data_length reflects data, while index_length reflects indexes. For InnoDB, both values are approximate: they are based on allocated pages. This is normal for planning and locating large objects, but it is not an exact count of useful bytes.
Find the largest tables in the selected database
Replace the placeholder YOUR_DATABASE with the name of the required schema. Do not leave the placeholder in the working query, and do not substitute it together with quotes from untrusted external input.
SELECT
table_name,
engine,
table_rows,
ROUND(data_length / 1024 / 1024, 2) AS data_mb,
ROUND(index_length / 1024 / 1024, 2) AS index_mb,
ROUND((data_length + index_length) / 1024 / 1024, 2) AS total_mb
FROM information_schema.tables
WHERE table_schema = 'YOUR_DATABASE'
AND table_type = 'BASE TABLE'
ORDER BY (data_length + index_length) DESC
LIMIT 20;
The condition table_type = 'BASE TABLE' excludes views. The limit LIMIT 20 retains the first twenty tables and does not affect the data. The field table_rows for InnoDB is an approximate estimate and may differ significantly from the exact row count.
Separate data from indexes
A large index is not necessarily redundant. It can accelerate critical queries. However, a table where indexes are significantly heavier than the data warrants separate verification: which indexes are used, whether there are duplicate composite keys, and how the record changes.
SELECT
table_name,
ROUND(data_length / 1024 / 1024, 2) AS data_mb,
ROUND(index_length / 1024 / 1024, 2) AS index_mb,
ROUND(
index_length / NULLIF(data_length, 0),
2
) AS index_to_data_ratio
FROM information_schema.tables
WHERE table_schema = 'YOUR_DATABASE'
AND table_type = 'BASE TABLE'
ORDER BY index_length DESC
LIMIT 20;
The function NULLIF protects the calculation from division by zero. The coefficient helps sort candidates but does not prove index redundancy. The decision to remove an index requires analyzing queries, unique constraints, and a backup; this is a separate task not covered in this guide.
Why figures may be outdated
MySQL caches table statistics. By default, the cache validity period can be up to 24 hours. A query against INFORMATION_SCHEMA may return an outdated estimate after a large data load or deletion.
The ANALYZE TABLE team updates statistics, but this is a modification operation for service data that can affect load and query plans. Do not run it automatically just for a pretty report. If fresh estimates are needed, coordinate the window and consequences with the administrator.
What is excluded from table totals
Binary logs and replication relay logs.
Redo and undo logs, the system tablespace, and InnoDB service files.
Temporary tables and temporary query files.
Backups, dumps, and application logs located near the database directory.
Free space within the shared tablespace that cannot be unambiguously attributed to a single table.
Therefore, for the task of "why the disk is running out," the query is supplemented with a check of the file system and MySQL configuration. For the task of "which tables are growing," it is more useful to save the results of the same query by date and compare the growth.
Criteria for a completed check
The MySQL version and the name of the analyzed schema have been recorded.
Database sizes and the first twenty tables have been retrieved.
Data and indexes were reviewed separately, but no conclusions on deletion were drawn based on a single coefficient.
The time of data retrieval and the possible age of the statistics were noted.
Free disk space was checked separately from the table assessment.
If the growth is unexpected, the table owner and the period for data comparison were identified.
Diagnostic SELECT queries are safer than attempting to shrink a table immediately, but on a large instance, even reading metadata can take time. If the server is already overloaded or replication is lagging, stop after the minimal query and coordinate further steps with the database administrator.

Обсуждение 0
Делись опытом и задавай вопросы. Комментарии без ссылок появляются после проверки редактором.
Пока никто не написал. Начни обсуждение.