How to Optimize MySQL Tables

Introduction

Optimizing MySQL tables helps reorder information in a dedicated storage server to improve data input and output speeds. However, knowing when to use each optimization function and how to apply them to your situation is key to viable table maintenance.

This article provides practical tips and functions for MySQL table optimization.

How to Optimize MySQL Tables

Prerequisites

  • MySQL version 8+ installed and configured (we are using 8.4).
  • Access to the command prompt or command line.
  • Fragmented database tables.

Why Should You Optimize MySQL Tables?

Unoptimized MySQL tables result from frequent update and delete queries, leading to fragmentation. The consequences are:

  • The database table takes up more space on disk than it requires.
  • Querying data takes more time than it should.

MySQL table optimization rearranges data inside a database table. It helps free up unused space and improve query speeds.

Note: For additional performance tuning techniques, see How to Improve MySQL Performance with Tuning.

When Should You Optimize MySQL Tables?

Tables where information in a database continually updates, such as transactional databases, are the most likely candidates for optimization. However, optimizing large tables takes longer, and it locks tables. Locking a table for several hours may disrupt system operations.

For InnoDB engine tables, consider trying one of the following:

  • Temporarily drop indexes. If a table and queries can function without indexes, a viable option is to drop the indexes, optimize, and add back the indexes. In some cases, this approach is faster than immediately optimizing.
  • Focus on the primary index. Analyze which values benefit from defragmentation. Choosing the wrong index can lead to more fragmentation.

Find Tables for Optimization

There are multiple ways to find tables and analyze them for optimization. Start by connecting to your MySQL database:

USE [database_name];

Depending on your use case, try the queries below to see how to find optimization candidates.

Tip 1: Show Unused Space in Table

Check the status of a desired table with:

SHOW TABLE STATUS LIKE "[table_name]" \G
SHOW TABLE STATUS data_length and data_free command output

The output shows general information about the provided table. The following two metrics (in bytes) are essential:

  • Data_length. Represents the total space used by the table.
  • Data_free. Shows the unused space allocated to the table.

Tip 2: Show Unused Space for All Tables

The information schema stores metadata about a database schema. To check the allocated unused data for all tables in a schema, run:

SELECT table_name, data_length, data_free
FROM information_schema.tables
WHERE table_schema='[schema_name]'
ORDER BY data_free DESC;
SELECT information_schema data_length and data_free output

The query displays the name of the table, the total space, and unused allocated space. By default, the values print in bytes.

Note: To display information for all databases, omit the line: WHERE table_schema='[schema name]'.

Tip 3: Display Data in Megabytes

To print the data in megabytes, use:

SELECT table_name, 
ROUND(data_length/1024/1024) as DATA_LENGTH_MB,
ROUND(data_free/1024/1024) as DATA_FREE_MB
FROM information_schema.tables
WHERE table_schema='[schema_name]'
ORDER BY data_free DESC;
SELECT data_length and data_free in MB output

The example tables are not heavily fragmented. However, using optimize table helps free up some space from the test_table.

Optimize MySQL Tables via Command Line

There are multiple ways to optimize tables by defragmentation. However, the general steps you perform are similar.

Tip 1: Optimize Tables via OPTIMIZE TABLE Command

MySQL provides a specific command for optimizing a table:

OPTIMIZE TABLE [table_name];
OPTIMIZE TABLE output

The output shows an informative status message about the actions and the results of the optimization in a table. The command does not reflect the changes immediately due to caching.

To clear any cached data about the table size and free space, flush all tables:

FLUSH TABLES;
FLUSH TABLES output

Then, analyze the table to confirm that the optimization has been applied and to update the table statistics:

ANALYZE TABLE [table_name];
ANALYZE TABLE output

This command sequence ensures that the table is fully optimized and its statistics are up to date.

OPTIMIZE TABLE Command in Different Storage Engines

The OPTIMIZE TABLE command behavior depends on the storage engine used for the table:

  • InnoDB. The command rebuilds the table to reclaim unused space. The operation creates a temporary table copy and replaces the original table with the optimized one. The process requires significant disk space temporarily for large tables.
  • MyISAM. The command reorganizes data to eliminate fragmentation, sorts indexes, and updates the table's statistics. Optimization is faster and requires less disk space.
  • Memory. OPTIMIZE TABLE has no effect on these tables because the data is stored in memory and there is no fragmentation.
  • CSV. The command recognizes the storage engine, but there are no significant performance improvements.
  • Archive. The command compresses the table into a smaller and compact format.

Tip 2: Optimize Multiple Tables at Once

To optimize multiple tables at once, use:

OPTIMIZE TABLE [table_name_1], [table_name_2];
OPTIMIZE TABLE multiple tables output

The result shows the status of the optimization for each optimized table. Proceed to flush and analyze the tables as described in Tip 1.

Tip 3: Optimize Tables via mysqlcheck Command

Perform table optimization through the Linux terminal with:

sudo mysqlcheck -o [schema] [table] -u [username] -p [password]

For example, to perform the check on a schema named test_db and a table named test_table using the root user credentials, run:

sudo mysqlcheck -o test_db test_table -u root -p
sudo mysqlcheck terminal output

Provide the password when prompted.

Note: Getting an access denied error? Read our guide on how to handle the issue: How to Solve MySQL Error: Access denied for user root@localhost.

To perform the optimization on multiple tables, separate each table name with a space:

sudo mysqlcheck -o [schema] [table_name_1] [table_name_2] -u [username] -p

Optimize MySQL Tables via GUI

Another way to optimize tables in MySQL is using the GUI. Most database management GUI tools offer a similar method to optimize tables.

The steps below show how to do this via MySQL Workbench:

Note: See our guide on how to install MySQL workbench to try the GUI method.

1. Start MySQL Workbench and connect to the database instance.

MySQL Workbench connections list

Provide the user's password when prompted.

2. In the left panel, navigate to the Schemas view.

MySQL Workbench schemas view

3. Expand the desired database schema, then expand Tables.

MySQL Workbench database schema tables expanded

4. Right-click any table name -> Table Maintenance.

MySQL Workbench table maintenance

5. Switch to the Tables tab.

MySQL Workbench table maintenance tables tab

6. Select the table name from the list and click Optimize Table in the right pane.

MySQL Workbench Optimize Table button

The action opens a pop-up and shows the optimization results.

After Optimization

The results of the optimization change the values of data_length and data_free of the optimized table.

Values before and after optimization of a MySQL table

Both values are lowered, indicating:

  • The optimization freed the unused allocated memory.
  • The overall memory of the database is lower because of the released space.

Conclusion

Optimizing MySQL tables requires careful consideration. This tutorial should help you with some practical guidance and tips on when to optimize MySQL tables.

For more SQL optimization tools, check out our review of the 13 Best SQL Query Optimization Tools.

Was this article helpful?
YesNo
Milica Dancuk
Milica Dancuk is a technical writer at phoenixNAP with a passion for programming. With a background in Electrical Engineering and Computing, coupled with her teaching experience, she excels at simplifying complex technical concepts in her writing.
Next you should read
7 Best Website Speed and Performance Testing Tools
June 3, 2019

There are programs that answer two of the most common questions web administrators and SEO's keep asking when it comes to server response time: How fast...
Read more
What Is Data Replication?
June 17, 2021

Database replication is used to improve data security, increase availability and performance, and make the database more robust. This tutorial covers different methods for database replication.
Read more
MySQL Commands Cheat Sheet
January 20, 2021

Need a reference sheet for all the important MySQL commands? Check out this MySQL Commands article which includes a downloadable MySQL cheat sheet in PDF format.
Read more
How to Create or Add an Index in MySQL With Examples
June 18, 2024

An index is an integral part of MySQL, helping with organizing and searching information more easily. This guide explains how to add an index to new...
Read more