Optimize all MySQL databases with one command
Thursday, September 15th, 2011A frequent problem we have is the clutter of MySQL databases created by shared webhosting customers. In order to maintain a well performing MySQL server we now and then have to optimize the MySQL tables. Doing this by hand, or waiting until the user does this is no option, therefore, we run this command, through a cron job:
First, we create a user named mysql_optimizer (with a strong password) and give it select and insert priveleges on the databases. You do not want your root user to be used in a cronjob!
mysql> GRANT SELECT, INSERT ON *.* TO ‘mysql_optimizer’@'localhost’ identified by ‘strong password’; mysql> flush privileges; mysql> exit;
Second thing is setting up the crontab, this time a weekly simple schedule:
> crontab -e # MySQL weekly optimisation 0 0 * * 0 /usr/bin/mysqlcheck -Aos --optimize -u mysql_optimizer -pstrongpassword > /dev/null 2>&1
That’s it!