Introduction
OPTIMIZE TABLE and mysqldump solve different maintenance problems. OPTIMIZE TABLE reorganizes a table’s physical storage and can reclaim disk space for supported engines. mysqldump creates a logical backup by exporting schema and row data as SQL statements. Optimizing a table does not remove free physical pages from the SQL dump, so it should not be scheduled solely to make a logical dump smaller or faster to restore.
Use optimization when storage reclamation or table reorganization is justified, and treat the backup as a separate operation with its own consistency and recovery checks. This guide explains what each operation does, how to choose tables carefully, and how to avoid running a costly rebuild as an automatic pre-backup step.
What OPTIMIZE TABLE Actually Changes
Fragmentation and reclaimable disk space are engine-specific. OPTIMIZE TABLE reorganizes table and index storage; it does not change the rows selected by a logical dump. For InnoDB, MySQL maps the operation to a table rebuild (ALTER TABLE ... FORCE) and can reclaim space to the operating system when the table uses a separate .ibd file. Space in the shared system tablespace generally remains allocated to InnoDB for reuse. For MyISAM, optimization can defragment the data file and reclaim unused space.
The storage benefit is not a promise of a smaller .sql file. A logical dump serializes schema and row values, not unused pages from the source files. If the dump is compressed, its size depends on the exported SQL and compression settings. A table rebuild can improve physical layout or I/O for later database operations, but it also consumes I/O, temporary disk space, and sometimes locks. Check the exact MySQL version and storage engine before scheduling it.
Select Tables Explicitly; Do Not Optimize the Whole Database Blindly
OPTIMIZE TABLE takes table names, not a database name. Do not interpolate an unchecked database name into a SQL statement, and do not treat every positive DATA_FREE estimate as proof that a table should be rebuilt. Inspect candidates, confirm the engine and expected benefit, and run maintenance against a reviewed table list during a suitable window.
For example, inspect the table engine and free-space estimate first:
SELECT TABLE_NAME, ENGINE, DATA_LENGTH, INDEX_LENGTH, DATA_FREEFROM information_schema.TABLESWHERE TABLE_SCHEMA = 'production_db'ORDER BY DATA_FREE DESC;If a specific table is a justified candidate, run the statement for that table by name:
OPTIMIZE TABLE `production_db`.`orders_archive`;This is a separate maintenance operation, not a prerequisite for mysqldump. On supported MySQL 8.4 InnoDB versions, OPTIMIZE TABLE uses online DDL for regular tables, which permits concurrent DML for much of the rebuild; it still needs brief exclusive metadata locks during prepare and commit, and documented exceptions such as tables with FULLTEXT indexes can use a table-copy method. MyISAM and older server versions can have different locking behavior. Consult the manual for the exact server version and engine, and test on representative data before production use.
Treat DATA_FREE as an estimate, not an automatic trigger
The DATA_FREE column is useful for screening, but it is not an exact measure of waste in every engine. MySQL documents that InnoDB reports free space for the tablespace containing the table. With a shared tablespace, a row can describe shared space rather than reclaimable space in that one table; partitioned-table values are estimates. Table statistics can also be cached. Therefore, do not run a fleet-wide OPTIMIZE TABLE just because DATA_FREE > 0.
Start with a read-only inventory and compare it with the actual file layout and workload:
SELECT TABLE_NAME, ENGINE, DATA_LENGTH, INDEX_LENGTH, DATA_FREEFROM information_schema.TABLESWHERE TABLE_SCHEMA = 'production_db' AND TABLE_TYPE = 'BASE TABLE'ORDER BY DATA_FREE DESC;For a partitioned table, sum partition statistics instead of assuming the table-level estimate is exact:
SELECT PARTITION_NAME, DATA_FREEFROM information_schema.PARTITIONSWHERE TABLE_SCHEMA = 'production_db' AND TABLE_NAME = 'orders_archive';Use these values to identify candidates for investigation, not as a command generator. Consider recent delete/update volume, table growth, storage-engine behavior, workload patterns, and whether file-per-table is enabled. If the freed space will be reused by future inserts, returning it to the operating system may not be worth a rebuild. Record the table size, engine, server version, and reason for maintenance before scheduling the operation.
Create a Consistent Logical Dump
For InnoDB, --single-transaction requests a consistent snapshot without locking every table for the full dump. It does not make MyISAM or MEMORY tables transactional, and concurrent DDL can invalidate the snapshot. If a backup mixes engines, plan consistency for the nontransactional tables separately. Use --quick for large tables; it is enabled by --opt by default in common MySQL versions, but making it explicit documents the memory behavior.
A straightforward compressed backup command is:
set -o pipefailumask 077DB_NAME='production_db'DUMP_FILE="/backups/mysql/${DB_NAME}_$(date +%Y%m%d_%H%M%S).sql.gz"
mysqldump --single-transaction --quick --routines --triggers --events \ --databases "$DB_NAME" | gzip > "$DUMP_FILE"The example requires a configured credential option file or another secure authentication method; do not put a password directly on the command line. pipefail ensures a failing mysqldump is not hidden by a successful gzip. In production, also check available space, capture the exit status, alert on failure, and test restores regularly. A dump that merely exists is not evidence of a recoverable backup.
Critical mysqldump Flags for Large and Fragmented Tables
The mysqldump utility supports several flags that interact with the optimization process. Understanding these flags prevents common pitfalls, especially when dealing with large tables or high-traffic databases.
The --quick flag streams rows from the server instead of buffering an entire table before writing it. It is useful for large exports because it limits client-side memory use. It is included in --opt, which is enabled by default in common MySQL versions, but specifying it explicitly makes the intended behavior clear. --single-transaction gives transactional tables such as InnoDB a consistent snapshot without holding table locks for the entire dump. It does not apply to MyISAM or MEMORY tables, and concurrent DDL can affect consistency.
For MyISAM and MEMORY tables, --single-transaction does not provide a consistent snapshot. Choose a locking strategy that matches the engines and workload. --lock-tables locks tables in each database while they are dumped, but does not guarantee a single consistent point across multiple databases. For mixed-engine backups requiring cross-table consistency, plan a maintenance window or use a backup method suited to that requirement.
# InnoDB logical dumpmysqldump --single-transaction --quick --databases dbname > dump.sql
# Nontransactional tables: assess locking and write impact firstmysqldump --lock-tables --quick --databases dbname > dump.sqlThe second command is an example for a nontransactional database; do not combine --single-transaction and --lock-tables, because MySQL treats those options as mutually exclusive. For databases containing both transactional and nontransactional tables, choose an explicit consistency plan instead of assuming one flag covers every engine.
--routines, --triggers, and --events include stored routines, triggers, and events that are otherwise omitted. Confirm these objects are included when you need a complete logical backup.
Avoid concurrent DDL during a single-transaction dump
For InnoDB tables, --single-transaction starts a consistent read, but the snapshot is not isolated from schema changes. MySQL warns against running ALTER TABLE, CREATE TABLE, DROP TABLE, RENAME TABLE, or TRUNCATE TABLE on dumped tables while the dump is in progress. Coordinate schema migrations and backup windows so those DDL statements cannot race with the export. Long-running dumps also keep a read view open; monitor transaction age and undo-history growth on busy systems, and do not leave abandoned dump sessions running indefinitely.
A useful operational sequence is:
- Confirm the database and storage engines included in the backup.
- Pause or coordinate deployment jobs that can run DDL on those tables.
- Start the dump with the consistency options appropriate for the engines.
- Check both the
mysqldumpand compression exit statuses, then verify that the output is non-empty and readable. - Resume schema changes only after the dump completes.
A command that returns zero is a useful signal, not a recovery test. Schedule periodic restores to an isolated test server and validate representative tables, routines, triggers, and application-level checks.
Trade-offs: Performance Impact and Downtime
Optimization can be resource-intensive and may need substantial temporary disk space. Locking and online behavior depend on engine, MySQL version, and DDL algorithm; do not assume every operation takes a full-duration write lock or runs without impact. Check the server’s documentation and test on representative data, then schedule it when its I/O and lock effects are acceptable.
For a large logical export, --quick controls client-side row buffering; it does not make the dump smaller and does not replace table optimization. If space reclamation is not the goal, skip OPTIMIZE TABLE and run the logical backup using an appropriate consistency strategy. For physical backup size and restore-time needs, evaluate a physical backup tool rather than expecting a logical dump to preserve the source table’s storage layout.
Measure the maintenance result
Before optimizing, save a baseline of the table’s engine, approximate data and index sizes, and the relevant tablespace or file size. Run the maintenance command in a controlled window and capture its result set. Then collect the same measurements again. An OPTIMIZE TABLE result of status: OK means the statement completed; it does not prove a particular number of bytes were returned to the operating system or that application queries became faster.
Use a short change record to make the decision auditable:
- MySQL version, storage engine, and whether the table has its own tablespace.
- Why this table is a candidate and what measurement supports that decision.
- Available disk space before the rebuild and the expected temporary-space requirement.
- The operation’s start/end time, result rows, and any lock or I/O symptoms.
- Before/after physical size and the query or workload used to assess performance.
Avoid running multiple large rebuilds concurrently. They can compete for disk bandwidth and temporary space, making the database slower even when each statement is supported online. If the measured benefit is negligible or free extents will be reused by normal writes, leave the table alone and revisit only when the workload changes.
Keep credentials and output files safe
Use a MySQL option file with restrictive permissions or the supported login-path mechanism rather than placing a password in a shell command. Command-line passwords can be exposed through shell history or process listings. Keep backup files readable only by the backup account, create the destination directory before the job runs, and check that the filesystem has enough space for both the uncompressed stream and any temporary files used by the server.
For a compressed pipeline, keep set -o pipefail enabled and write to a temporary file on the same filesystem before renaming it to the final name. This prevents a failed export from replacing the last known-good backup with a partial file:
set -euo pipefailumask 077DB_NAME='production_db'DUMP_DIR='/backups/mysql'mkdir -p "$DUMP_DIR"TMP_FILE="$DUMP_DIR/.${DB_NAME}_$(date +%Y%m%d_%H%M%S).sql.gz.tmp"FINAL_FILE="${TMP_FILE%.tmp}"
mysqldump --single-transaction --quick --routines --triggers --events \ --databases "$DB_NAME" | gzip > "$TMP_FILE"test -s "$TMP_FILE"gzip -t "$TMP_FILE"mv -- "$TMP_FILE" "$FINAL_FILE"printf 'Created %s\n' "$FINAL_FILE"This example assumes the client credentials are already configured securely and the backup directory is on a filesystem with sufficient capacity. Add retention and off-host replication separately; a local dump alone does not protect against loss of the host or storage volume.
Online schema change tools such as Percona Toolkit’s pt-online-schema-change may suit some large-table maintenance tasks, but they have their own operational requirements and are not a drop-in replacement for a tested backup. Choose maintenance tooling based on the storage goal, table engine, server version, and recovery plan.
Troubleshooting Common Errors
Operational database work often involves troubleshooting specific error messages. When optimizing tables before a dump, two common errors occur.
The first error is Lock wait timeout exceeded; try restarting transaction. This error indicates that another session holds a write lock on the table that the optimization process cannot acquire. It usually happens when the database is under heavy write load. The optimization process retries acquiring the lock for a specified duration (default is 50 seconds in many configurations). If it cannot acquire the lock, the command fails. The solution is to check the current locks using SHOW ENGINE INNODB STATUS or SHOW PROCESSLIST to identify the blocking process and either wait for it to complete or terminate it if it is a runaway query.
The second error is Table 'database.table_name' was marked as crashed and should be repaired. This error indicates that the table file has become corrupted, often due to a power failure or a crash while writing. OPTIMIZE TABLE includes a repair step for MyISAM tables. If the table is in this state, the command will attempt to repair it. However, if the corruption is severe, the table may remain in a crash-recoverable state. In this case, the database administrator must use the REPAIR TABLE command or, if that fails, restore from a previous backup snapshot.
A dump can fail with Can't create/write to file ... (Errcode: 28 - No space left on device) when the server or destination filesystem runs out of space. Check the exact path in the error, free space, inodes, and the destination volume. --quick reduces client-side buffering, but it does not remove the need for adequate temporary and destination storage.
Schedule Backups Separately from Table Maintenance
A backup schedule and a storage-maintenance schedule have different goals. Run and verify logical backups at the required recovery-point interval; schedule OPTIMIZE TABLE separately, only for tables where reclaiming physical space or reorganizing storage is justified. This avoids rebuilding every table on every backup run and makes the resource cost easier to monitor.
A simple cron entry can run a tested backup script at a quiet hour:
# Run the logical backup daily at 03:000 3 * * * /usr/local/bin/mysql_logical_backup.sh >> /var/log/mysql_backup_cron.log 2>&1The script should use protected credentials, record failures, and notify an operator. Do not assume cron automatically emails on failure unless the host’s mail delivery is configured. Keep logs rotated and periodically test a restore from the produced backup.
Restore Test and Maintenance Checklist
A successful mysqldump exit status confirms that the export command completed; it does not prove that the backup can be restored. Restore it to an isolated test instance, validate required databases and objects, and document the recovery procedure. A logical restore creates table data from SQL statements; it does not preserve the physical layout of the source tables.
Before any optimization, confirm the exact engine and server version, review the table and DATA_FREE estimate, check disk headroom and workload, and test the operation on representative data. Then run OPTIMIZE TABLE only for the named table or tables whose physical storage warrants it. Do not make it an unconditional step before each dump.
For each logical backup, choose a consistency strategy compatible with all included storage engines, use --single-transaction for transactional tables where appropriate, and account for concurrent DDL. Include routines, triggers, and events when required. Finally, verify the dump file, record its size and checksum if useful, and test restoring it on a schedule.