0% found this document useful (0 votes)
6 views

Unit 3

Uploaded by

jnidhi88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit 3

Uploaded by

jnidhi88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Maintaining MySQL tables is essential for ensuring optimal performance and reliability of your

database. Here are some key aspects of MySQL table maintenance:


1. Regular Backups
• Backup Strategy: Regularly back up your databases to prevent data loss. Use tools like
mysqldump or mysqlpump for logical backups, or consider using physical backups with tools
like Percona XtraBackup.
• Automate Backups: Set up automated backup schedules to ensure you have recent backups
without manual intervention.
2. Optimizing Tables
• Optimize Tables Command: Use the OPTIMIZE TABLE command to defragment tables and
reclaim unused space. This can help improve performance, especially for InnoDB and
MyISAM tables.
OPTIMIZE TABLE table_name;
• Analyze Tables Command: Use the ANALYZE TABLE command to update table statistics
for the query optimizer.
ANALYZE TABLE table_name;
3. Check and Repair Tables
• Check Tables Command: Use CHECK TABLE to check the integrity of tables and identify
any issues.
CHECK TABLE table_name;
• Repair Tables Command: If you find issues, use REPAIR TABLE to fix them (mostly for
MyISAM tables).
REPAIR TABLE table_name;
4. Index Maintenance
• Optimize Indexes: Regularly review and optimize your indexes to ensure efficient query
performance. Remove unused indexes and create new ones as needed.
• Indexing Strategy: Use proper indexing strategies to balance query performance and write
efficiency.
5. Data Cleanup
• Archiving Old Data: Periodically archive or delete old or unused data to reduce the size of
your tables and improve performance.
• Purging Logs: Clean up binary logs, error logs, and slow query logs if they are no longer
needed.
6. Monitoring Performance
• Query Performance: Use the SHOW PROCESSLIST command to monitor running queries
and identify slow queries.
• Slow Query Log: Enable and review the slow query log to identify and optimize slow-running
queries.
• Performance Schema: Use MySQL’s Performance Schema to get detailed performance
metrics.
7. Schema Changes
• Plan Schema Changes: When making changes to the database schema, such as adding or
dropping columns, plan and test these changes in a staging environment before applying them
to production.
• Use pt-online-schema-change: For minimal downtime during schema changes, consider using
tools like Percona's pt-online-schema-change.
8. Database Security
• User Privileges: Regularly review and update user privileges to ensure the principle of least
privilege is followed.
• Security Patches: Keep MySQL up to date with the latest security patches and updates.
9. Configuration Tuning
• Tune Parameters: Regularly review and tune MySQL configuration parameters based on your
workload. Parameters such as innodb_buffer_pool_size, query_cache_size, and
max_connections can have a significant impact on performance.
• Use MySQL Tuner: Tools like MySQLTuner can help identify areas for improvement in your
configuration.
10. Documentation and Best Practices
• Document Changes: Keep detailed records of any changes made to the database schema or
configuration.
• Follow Best Practices: Adhere to MySQL best practices for schema design, query
optimization, and backup procedures.
Regular maintenance and monitoring can help ensure that your MySQL databases run smoothly and
efficiently.
Here’s a detailed overview of various MySQL table maintenance operations, including commands and
their purposes:
1. Table Maintenance
• Purpose: General upkeep of tables to ensure performance and data integrity.
• Commands:
o Analyze Table: Updates statistics about the table, which helps the optimizer make
better decisions.
ANALYZE TABLE table_name;
o Optimize Table: Reclaims unused space and defragments the table.
OPTIMIZE TABLE table_name;
o Repair Table: Fixes issues with MyISAM tables (less common with InnoDB tables).
REPAIR TABLE table_name;
o Check Table: Verifies the integrity of the table.
CHECK TABLE table_name;
2. Backup and Restore
• Backup Table:
o Purpose: To create a copy of the table data, typically for backup purposes.
o Commands:
▪ Using mysqldump: Creates a logical backup of a table.
mysqldump -u user -p database_name table_name > table_backup.sql
▪ Using SELECT INTO OUTFILE: Exports table data to a file.

SELECT * INTO OUTFILE '/path/to/backup_file.csv' FIELDS TERMINATED BY ',' ENCLOSED BY


'"' LINES TERMINATED BY '\n' FROM table_name;
• Restore Table:
o Purpose: To restore a table from a backup.
o Commands:
▪ Using mysql: Restores a table from a dump file.
mysql -u user -p database_name < table_backup.sql
▪ Using LOAD DATA INFILE: Imports data from a file.
LOAD DATA INFILE '/path/to/backup_file.csv' INTO TABLE table_name FIELDS TERMINATED
BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';
3. Checksum Table
• Purpose: Verifies the integrity of data by generating and checking checksums.
• Command:
o Generate Checksum: For MyISAM tables, use the CHECKSUM TABLE command.
CHECKSUM TABLE table_name;
o This command provides a checksum value that can be used to verify data integrity.
4. Moving Tablespace
• Purpose: To relocate the tablespace files, which might be necessary for performance tuning or
disk space management.
• Command/Process:
o InnoDB Tablespace Relocation:
1. Prepare the Tablespace: Ensure the table is using the FILE_PER_TABLE
setting.
2. Alter Tablespace: Move the tablespace file.
sql

ALTER TABLE table_name TABLESPACE = 'new_tablespace_location';


3. Move Files: Physically move the .ibd files to the new location.
4. Update Configuration: Ensure that the MySQL configuration points to the
new location.
5. Information Schema
• Purpose: Provides metadata about the database objects (e.g., tables, columns, indexes) and
their status.
• Useful Tables in Information Schema:
o information_schema.tables: Contains information about all tables in the database.
sql

SELECT * FROM information_schema.tables WHERE table_schema = 'database_name';


o information_schema.columns: Provides details about columns in the tables.
sql

SELECT * FROM information_schema.columns WHERE table_schema = 'database_name' AND


table_name = 'table_name';
o information_schema.statistics: Shows index information.

SELECT * FROM information_schema.statistics WHERE table_schema = 'database_name' AND


table_name = 'table_name';
o information_schema.engines: Lists storage engines and their status.
sql

SELECT * FROM information_schema.engines;


Summary
Regularly performing these maintenance tasks will help ensure the health and efficiency of your
MySQL databases. Each command and process serves a specific purpose in maintaining performance,
data integrity, and backup/recovery readiness.
In MySQL, both the Information Schema and the Performance Schema provide valuable insights
into the database system, but they serve different purposes. Here’s a detailed look at each:
Information Schema
The Information Schema is a set of read-only views that provide metadata about the database's objects.
It’s essentially a database within your database that contains information about other databases, tables,
columns, users, and more.
Key Tables in Information Schema:
1. information_schema.tables
o Purpose: Provides information about tables in the database.
o Important Columns:
▪ TABLE_SCHEMA: Name of the database.
▪ TABLE_NAME: Name of the table.
▪ TABLE_TYPE: Type of table (e.g., BASE TABLE, VIEW).
▪ ENGINE: Storage engine used (e.g., InnoDB, MyISAM).
sql

SELECT * FROM information_schema.tables WHERE table_schema = 'database_name';


2. information_schema.columns
o Purpose: Contains details about columns in the tables.
o Important Columns:
▪ TABLE_SCHEMA: Name of the database.
▪ TABLE_NAME: Name of the table.
▪ COLUMN_NAME: Name of the column.
▪ DATA_TYPE: Type of the data stored in the column.
▪ IS_NULLABLE: Whether the column can contain NULL values.
sql

SELECT * FROM information_schema.columns WHERE table_schema = 'database_name' AND


table_name = 'table_name';
3. information_schema.statistics
o Purpose: Provides information about indexes and their columns.
o Important Columns:
▪ TABLE_SCHEMA: Name of the database.
▪ TABLE_NAME: Name of the table.
▪ COLUMN_NAME: Name of the indexed column.
▪ INDEX_NAME: Name of the index.
▪ NON_UNIQUE: Whether the index allows duplicates.
sql

SELECT * FROM information_schema.statistics WHERE table_schema = 'database_name' AND


table_name = 'table_name';
4. information_schema.processlist
o Purpose: Shows information about the currently running processes.
o Important Columns:
▪ ID: Process ID.
▪ USER: User executing the query.
▪ HOST: Host from which the user is connected.
▪ DB: Database being accessed.
▪ COMMAND: Command being executed (e.g., Query, Sleep).
▪ TIME: Time the process has been running.
sql

SELECT * FROM information_schema.processlist;


5. information_schema.engines
o Purpose: Lists storage engines available in MySQL and their statuses.
o Important Columns:
▪ ENGINE: Name of the storage engine.
▪ SUPPORT: Whether the engine is supported (YES, NO, or DEFAULT).
▪ COMMENT: Description of the engine.
sql

SELECT * FROM information_schema.engines;


Performance Schema
The Performance Schema is a diagnostic tool that provides a wealth of information about the
performance of MySQL queries and the internal operations of the server. It collects and stores
performance-related data, which can be queried to understand and optimize database performance.
Key Tables in Performance Schema:
1. performance_schema.events_statements_summary_by_digest
o Purpose: Provides summarized statistics about SQL statements.
o Important Columns:
▪ DIGEST: A hash of the SQL statement.
▪ DIGEST_TEXT: The SQL statement.
▪ COUNT_STAR: Number of times the statement has been executed.
▪ SUM_TIMER_WAIT: Total time spent executing the statement.
sql

SELECT * FROM performance_schema.events_statements_summary_by_digest;


2. performance_schema.events_waits_summary_by_instance
o Purpose: Summarizes wait events for different instances (e.g., file I/O, table locks).
o Important Columns:
▪ EVENT_NAME: Name of the wait event.
▪ SOURCE: Source of the event.
▪ COUNT_STAR: Number of wait events.
▪ SUM_TIMER_WAIT: Total wait time.
sql

SELECT * FROM performance_schema.events_waits_summary_by_instance;


3. performance_schema.threads
o Purpose: Provides information about MySQL threads.
o Important Columns:
▪ THREAD_ID: Identifier for the thread.
▪ NAME: Name of the thread.
▪ PROCESSLIST_ID: Corresponding ID in the process list.
▪ PROCESSLIST_USER: User of the thread.
▪ PROCESSLIST_DB: Database being used by the thread.
sql
SELECT * FROM performance_schema.threads;
4. performance_schema.file_summary_by_event_name
o Purpose: Provides summary information about file I/O events.
o Important Columns:
▪ EVENT_NAME: Name of the file event.
▪ COUNT_READ: Number of read operations.
▪ COUNT_WRITE: Number of write operations.
▪ SUM_TIMER_READ: Total time spent reading.
▪ SUM_TIMER_WRITE: Total time spent writing.
sql

SELECT * FROM performance_schema.file_summary_by_event_name;


5. performance_schema.memory_summary_by_account_by_event_name
o Purpose: Summarizes memory usage by account and event type.
o Important Columns:
▪ ACCOUNT: User account.
▪ EVENT_NAME: Name of the event.
▪ SUM_USED_MEMORY: Total memory used.
sql

SELECT * FROM performance_schema.memory_summary_by_account_by_event_name;


Summary
• Information Schema is mainly for querying metadata about the structure and status of
databases, tables, columns, and other objects.
• Performance Schema is designed for in-depth performance analysis and diagnostics,
providing detailed insights into query execution, wait events, and system resource usage.
Both schemas are critical for effective MySQL database management, offering tools for both
maintenance and optimization.

Introduction to MySQL ANALYZE TABLE statement


In MySQL, the query optimizer relies on table statistics to optimize query execution plans.
The table statistics help the query optimizer estimate the number of rows in a table that satisfy a
particular condition.
However, sometimes the table statistics can be inaccurate. For example, after you have done a lot of
data changes in the table such as inserting, deleting, or updating.
If the table statistics are not accurate, the query optimizer may pick a non-optimal query execution plan
that may cause a severe performance issue.
To address this issue, MySQL provides the ANALYZE TABLE statement that updates these statistics,
ensuring that the query optimizer has accurate information for efficient query planning.
The following ANALYZE TABLE statement performs a key distribution analysis:
ANALYZE TABLE table_name [, table_name];Code language: SQL (Structured Query Language) (sql)
In this syntax:
• table_name: The name of the table that you want to analyze. If you want to analyze multiple
tables, you separate them by commas.
This key distribution analysis is essential for understanding the distribution of key values within the
table. The query optimizer uses the results of this statement to optimize join operations and index usage.
The ANANLYZE TABLE statement works only with InnoDB, NDB, and MyISAM tables.
MySQL ANALYZE TABLE statement example
We’ll use the table from the sample database for the demonstration.
First, log in to the MySQL Server using the root account:
mysql -u root -pCode language: SQL (Structured Query Language) (sql)
It’ll prompt you to enter a password for the root account.
Second, switch the current database to classicmodels:
use classicmodels;Code language: SQL (Structured Query Language) (sql)
Third, analyze the customers table:
analyze table customers;Code language: SQL (Structured Query Language) (sql)
Output:
+-------------------------+---------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+-------------------------+---------+----------+----------+
| classicmodels.customers | analyze | status | OK |
+-------------------------+---------+----------+----------+
1 row in set (0.01 sec)Code language: SQL (Structured Query Language) (sql)
The output table has the following columns:
• Table: The table name that was analyzed.
• op: analyze or histogram.
• Msg_type: show the message type including status, error, info, note, or warning.
• Msg_text: an informational message.
Summary
• Use the MySQL ANALYZE TABLE statement to ensure that the query optimizer has accurate
and up-to-date table statistics, allowing it to generate optimal query execution plans.

The ANALYZE TABLE command in MySQL is used to analyze and update the key distribution
statistics for a table. These statistics help the MySQL query optimizer to make better decisions about
how to execute queries, particularly for selecting the best indexes.
Purpose of ANALYZE TABLE:
1. Update Statistics: It updates the index statistics of the table, which can improve the
performance of queries by ensuring that the optimizer has current information about data
distribution.
2. Query Optimization: Accurate statistics help the query optimizer to estimate the number of
rows that will be returned by queries and choose the most efficient execution plan.
Syntax:
sql
Copy code
ANALYZE TABLE table_name [, table_name2, ...];
• table_name: The name of the table you want to analyze.
• You can specify multiple tables in a single command, separated by commas.
Usage Example:
sql
Copy code
ANALYZE TABLE employees;
This command will analyze the employees table and update its index statistics.
What Happens When You Run ANALYZE TABLE:
• InnoDB Tables:
o Updates statistics about the distribution of values in the index columns.
o Collects information about index cardinality, which is used by the optimizer to estimate
the number of rows that will match a given query.
• MyISAM Tables:
o Rebuilds the index and updates index statistics.
o Fixes any inconsistencies in the index data.
Additional Considerations:
• Locking: The ANALYZE TABLE command locks the table while it performs the analysis,
which may impact performance if the table is large or heavily used.
• Frequency: It’s generally not necessary to run ANALYZE TABLE frequently. However, you
might want to run it after significant data modifications, such as large inserts, updates, or
deletions, to ensure that the optimizer has accurate statistics.
Example with Multiple Tables:
sql
Copy code
ANALYZE TABLE employees, departments, salaries;
This command will analyze the employees, departments, and salaries tables in one go.
Checking Table Status:
You can check the status of a table after running ANALYZE TABLE using:
sql
Copy code
SHOW TABLE STATUS LIKE 'employees';
This command will show you various details about the table, including the Data_free (unused space)
and Update_time.
Automated Statistics Updates:
• InnoDB automatically updates statistics periodically. For MyISAM tables, manual updates with
ANALYZE TABLE are often required.
Summary:
The ANALYZE TABLE command is a useful tool for maintaining accurate index statistics, which can
help improve query performance by providing the optimizer with up-to-date information. While it’s not
something that needs to be run daily, it’s a good practice to use it after making significant changes to
the data.

Introduction to MySQL CHECK TABLE statement


The CHECK TABLE statement allows you to check one or more tables for errors.
The following shows the syntax of the CHECK TABLE statement:
CHECK TABLE tbl_name, [,table_name]...
[option]Code language: SQL (Structured Query Language) (sql)
In this syntax:
First, specify one or more names of the tables you want to check for errors.
Second, specify one or more options that can be:
• FOR UPGRADE
• QUICK
• FAST
• MEDIUM
• EXTENDED
• CHANGED
The CHECK TABLE statement works for InnoDB, MyISAM, ARCHIVE, and CSV tables.
The storage engine may accept or ignore the option of the CHECK TABLE statement.

Type Storage Engines Meaning

QUICK Applies to InnoDB & Do not scan the rows for incorrect links.
MyISAM

FAST Applies to MyISAM. Check only tables that have not been properly closed.
Ignored for InnoDB.

CHANGED Applies to MyISAM. Check tables that have either been modified since the last check or have
Ignored for InnoDB. not been properly closed.

MEDIUM Applies to MyISAM. Scan rows to verify the validity of deleted links. This process also
Ignored for InnoDB. calculates a key checksum for the rows and checks it against the
calculated checksum for the keys.

EXTENDED Applies to MyISAM. Perform a complete key lookup for all keys associated with each row.
Ignored for InnoDB. This guarantees 100% consistency in the table but is a time-consuming
process.

The CHECK TABLE statement also checks views for problems. For example, it can check if a view
references tables that do not exist.
The CHECK TABLE returns a result set that includes four columns:

Column Value

Table The table name that has been checked

Op Always check

Msg_type status, error, info, note, or warning

Msg_text An informational message

The CHECK TABLE statement might generate multiple rows of information for each checked table or
view. The last row should have a Msg_type value of status and the Msg_text should typically be OK
MySQL CHECK TABLE statement examples
Let’s take some examples of using the CHECK TABLE statement.
1) Using the CHECK TABLE to check for errors in tables
First, log in to the MySQL database server using the root account:
mysql -u root -pCode language: SQL (Structured Query Language) (sql)
It’ll prompt you to enter the password. Enter the valid password to log in:
Enter password: ********Code language: SQL (Structured Query Language) (sql)
Second, switch the current database to classicmodels sample database:
use classicmodels;Code language: SQL (Structured Query Language) (sql)
Third, check the tables customers and products for errors:
CHECK TABLE customers, products;Code language: SQL (Structured Query Language) (sql)
Output:
+-------------------------+-------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+-------------------------+-------+----------+----------+
| classicmodels.customers | check | status | OK |
| classicmodels.products | check | status | OK |
+-------------------------+-------+----------+----------+
2 rows in set (0.03 sec)Code language: SQL (Structured Query Language) (sql)
The output shows that both tables have no errors.
2) Using the MySQL CHECK TABLE to check for errors in a view
First, create a database called test:
CREATE DATABASE IF NOT EXISTS test;Code language: SQL (Structured Query Language) (sql)
Second, switch to the test database:
USE test;Code language: PHP (php)
Third, create a table called employees in the test database:
CREATE TABLE employees(
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(255) NOT NULL
);Code language: SQL (Structured Query Language) (sql)
Fourth, create a view called contacts based on the employees table:
CREATE VIEW contacts AS
SELECT
concat_ws(' ', first_name, last_name) as name,
email,
phone
FROM
employees;Code language: SQL (Structured Query Language) (sql)
Fifth, drop the table employees:
DROP TABLE employees;Code language: SQL (Structured Query Language) (sql)
Finally, check the view contacts for the error:
CHECK TABLE contacts\G;Code language: SQL (Structured Query Language) (sql)
Output:
*************************** 1. row ***************************
Table: test.contacts
Op: check
Msg_type: Error
Msg_text: View 'test.contacts' references invalid table(s) or column(s) or function(s) or definer/invoker
of view lack rights to use them
*************************** 2. row ***************************
Table: test.contacts
Op: check
Msg_type: error Msg_text: Corrupt
2 rows in set (0.00 sec)

ERROR:
No query specifiedCode language: SQL (Structured Query Language) (sql)
Note that the \G instructs mysql to display the result in a more readable, vertical format rather than a
traditional horizontal, table-based layout.
The first row indicates that the view references an invalid table and the second row specifies that the
view is corrupt.
Summary
• Use the MySQL CHECK TABLE statement to check one or more tables or views for errors.
Introduction to MySQL REPAIR TABLE statement
During operation, your tables may be corrupted due to various reasons, such as hardware failures,
unexpected shutdowns, or software bugs.
To repair the possibly corrupted tables, you use the REPAIR TABLE statement. The REPAIR
TABLE statement can repair only tables that use MyISAM, ARCHIVE, or CSV storage engines.
Here’s the syntax of the REPAIR TABLE statement:
REPAIR TABLE table_name [, table_name] ...
[QUICK] [EXTENDED] [USE_FRM];Code language: SQL (Structured Query Language) (sql)
In this syntax:
• table_name: The name of the table you want to repair. The statement allows you to repair
multiple tables at once.
• QUICK: This is the default option that allows you to perform a quick repair. It is suitable for
most cases.
• EXTENDED: This option allows you to perform an extended repair. It may take longer however
can fix more complex issues.
• USE_FRM: This option re-creates the .frm file. It’ll help when the table definition file is
corrupted.
MySQL REPAIR TABLE statement examples
Let’s take some examples of using the REPAIR TABLE statement.
The following command performs a quick repair on the sample_table table:
REPAIR TABLE sample_table;Code language: SQL (Structured Query Language) (sql)
It’s equivalent to the following statement that uses the QUICK option explicitly:
REPAIR TABLE sample_table QUICK;Code language: SQL (Structured Query Language) (sql)
The following command performs an extended repair on the sample_table table:
REPAIR TABLE sample_table EXTENDED;Code language: SQL (Structured Query Language) (sql)
When you find that the table definition file (.frm) is suspected to be corrupted, you can use
the USE_FRM option to recreate it:
REPAIR TABLE sample_table USE_FRM;Code language: SQL (Structured Query Language) (sql)
Important notes on using the REPAIR TABLE statement
When using the REPAIR TABLE statement, you should consider the following important notes:
Making a backup before repairing tables
It’s important to make a backup of a table before you repair it. In some cases, the REPAIR
TABLE statement may cause data loss.
Table lock
The REPAIR TABLE statement requires a table lock during the repair process. If you issue queries to
the table, they will blocked until the repair is complete.
Storage Engines
The REPAIR TABLE statement only works with MyISAM, CSV, and ARCHIVE tables. It doesn’t
support tables of other storage engines.
Replication
If they run the REPAIR TABLE for the original tables, the fixes will not propagate to replicas.
Summary
• Use the REPAIR TABLE statement to repair possibly corrupted tables.
Introduction to MySQL OPTIMIZE TABLE statement
The OPTIMIZE TABLE statement allows you to reorganize the physical storage of table data to reclaim
unused storage space and improve performance when accessing the table.
In practice, you’ll find the OPTIMIZE TABLE statement useful in the following cases:
• Frequent deletions/updates: If a table has frequent updates or deletions, its data may be
fragmented. The OPTIMIZE TABLE statement can help rearrange the storage structure and
eliminate wasted space.
• Table with variable-length rows: Tables with variable-length data such as VARCHAR, TEXT,
and BLOB may become fragmented over time. By using the OPTIMIZE TABLE statement,
you can reduce the storage overhead.
• Significant data growth and shrinkage: If your database experiences significant growth &
shrinkage, you can run the OPTIMIZE TABLE periodically to maintain optimal storage
efficiency.
Overall, using the OPTIMIZE TABLE statement helps you optimize the storage space of table data and
improve the query performance.
The OPTIMIZE TABLE statement works with InnoDB, MyISAM, and ARCHIVE tables.
MySQL OPTIMIZE TABLE statement examples
Let’s take some examples of using the MySQL OPTIMIZE TABLE statement.
1) Using the MySQL OPTIMIZE TABLE statement for MyISAM tables
For MyISAM tables, the OPTIMIZE TABLE statement works as follows:
• Repair the table if it has deleted or split rows.
• Sort the index pages if they are not sorted.
• Update the table statistics if they are not up to date.
The following example illustrates the steps for optimizing a MyISAM table:
First, check the table status using the show table status statement:
SHOW TABLE STATUS LIKE '<table_name>'\GCode language: SQL (Structured Query Language)
(sql)
It’ll return the output like this:
*************************** 1. row ***************************
Name: <table_name>
Engine: MyISAM
Version: 10
Row_format: Dynamic
Rows: 5000
Avg_row_length: 44
Data_length: 440000
Max_data_length: 281474976710655
Index_length: 105472
Data_free: 220000
Auto_increment: 10001
Create_time: 2023-11-21 07:34:39
Update_time: 2023-11-21 07:38:43
Check_time: NULL
Collation: utf8mb4_0900_ai_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)Code language: SQL (Structured Query Language) (sql)
There are two important columns in the output regarding optimizing the table:
• The Data_length represents the space used by all rows in the table including any overhead as
row headers.
• The Data_free is the amount of free space (in bytes) in the data file. It indicates how much
space can potentially be reclaimed by the OPTIMIZE TABLE statement.
Second, optimize the table using the OPTIMIZE TABLE statement:
OPTIMIZE TABLE <table_name>;Code language: SQL (Structured Query Language) (sql)
Output:
+----------------+----------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+----------------+----------+----------+----------+
| test.text_data | optimize | status | OK |
+----------------+----------+----------+----------+
1 row in set (0.05 sec)Code language: SQL (Structured Query Language) (sql)
The Msg_text is OK which indicates the optimization is successful.
Third, check the status of the table again:
SHOW TABLE STATUS LIKE '<table_name>'\GCode language: SQL (Structured Query Language)
(sql)
If the table space is fragmented, you’ll see Data_free is zero:
*************************** 1. row ***************************
Name: <table_name>
Engine: MyISAM
Version: 10
Row_format: Dynamic
Rows: 5000
Avg_row_length: 44
Data_length: 440000
Max_data_length: 281474976710655
Index_length: 105472
Data_free: 0
Auto_increment: 10001
Create_time: 2023-11-21 08:03:12
Update_time: 2023-11-21 08:03:41
Check_time: NULL
Collation: utf8mb4_0900_ai_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)Code language: SQL (Structured Query Language) (sql)
2) Using the MySQL OPTIMIZE TABLE statement for InnoDB tables
When you run the OPTIMIZE TABLE statement on InnoDB tables, you’ll get the following output:
+--------+----------+----------+-------------------------------------------------------------------+
| Table | Op | Msg_type | Msg_text |
+--------+----------+----------+-------------------------------------------------------------------+
| test.t | optimize | note | Table does not support optimize, doing recreate + analyze instead |
| test.t | optimize | status | OK |
+--------+----------+----------+-------------------------------------------------------------------+
2 rows in set (0.05 sec)Code language: SQL (Structured Query Language) (sql)
The first message:
Table does not support optimize, doing recreate + analyze insteadCode language: SQL (Structured
Query Language) (sql)
It means that the OPTIMIZE TABLE does not optimize the InnoDB tables in the same way it optimizes
the MyISAM tables. Instead, the OPTIMIZE TABLE statement performs the following actions:
• First, create a new empty table.
• Second, copy all rows from the original table into the new table.
• Third, delete the original table and rename the new tables.
• Finally, run the ANALYZE statement to gather table statistics.
One caution is that you should avoid running the OPTIMIZE TABLE statement on a
large InnoDB table when the disk space is low, as it is likely to cause the server to run out of space
while attempting to recreate the large table.
Summary
• Use the OPTIMIZE TABLE statement to reorganize the physical storage of tables to reduce
disk space usage and improve query execution time.

You might also like