Overview
You can optimize your database via SSH to improve your website's efficiency. Optimizing reorganizes a table's physical storage to reduce space and improve access, while repairing fixes a possibly corrupted table.
How do I optimize a database via SSH?
The following uses SSH to optimize or repair tables in your database.
How do I check the database size via SSH?
Connect to a database via SSH and run the following query to view the size of the database in MB (do not replace any text or add any line breaks):
SELECT table_schema "database", sum(data_length + index_length)/1024/1024 "size in MB" FROM information_schema.TABLES GROUP BY table_schema;How do I optimize tables via SSH?
Log in to your server and run the mysqlcheck command to check, repair, and optimize tables. Make sure to replace the variables in the command with your database credentials.
[server]$ mysqlcheck -h HOSTNAME -u USERNAME -p -o DATABASE
You may see the following note in the command output:
Table does not support optimize, doing recreate + analyze instead
This message occurs when MySQL's InnoDB storage engine performs a different set of operations to optimize the table and can be safely disregarded.
View log data
You can output the log data into a file by adding the following to the end of the command:
>> results.txt
Then use the cat command to read the file:
cat results.txt
Use a cron job to optimize
Another option is to create a cron job to optimize using the mysqlcheck command.
Create a file named something like optimize-db.sh in your user's home directory.
Add this code to it (using your database credentials).
#!/bin/sh /usr/bin/mysqlcheck -o -v -u USERNAME -pPASSWORD -h MYSQL.EXAMPLE.COM DATABASENAME;
Create a cron job to run this file. The cron command may look like this:
/bin/sh /home/username/optimize-db.sh
A good practice is to run this on a monthly schedule.
How do I repair a table via SSH?
If you're seeing database errors, run this command to repair a corrupted table instead of optimizing it.
[server]$ mysql -u USERNAME -pPASSWORD -h HOSTNAME DATABASENAME -e "show tables" | grep -v Tables_in | grep -v "+" | gawk '{print "repair table " $1 ";"}' | mysql -u USERNAME -pPASSWORD -h HOSTNAME DATABASENAME