Optimize tables in MySQL automatically with PHP
Posted September 7th, 2008 in MySql and PHP
In previous posts I looked at how to optimize a MySQL table from the MySQL command line interface and from phpMyAdmin by using the optimize [tablename] command to free up unused space. In this post I will look at how to do this with a PHP script which could be run periodically to optimise all non-optimal MySQL tables.
The SQL we'll use to find tables which are non-optimal looks like this:
SHOW TABLE STATUS WHERE Data_free > [integer value]
substituting [integer value] for an integer value, which is the free data space in bytes. This could be e.g. 102400 for tables with 100k of free space. This will then only return the tables which have more than 100k of free space.
An alternative way of searching would be to look for tables that have e.g. 10% of overhead free space by doing this:
SHOW TABLE STATUS WHERE Data_free / Data_length > 0.1
The downside with this is that it would include small tables with very small amounts of free space so it could be combined with the first SQL query to only get tables with more than 10% overhead and more than 100k of free space:
SHOW TABLE STATUS WHERE Data_free / Data_length > 0.1 AND Data_free > 102400
Using the above SQL, the PHP code would look like this:
$res = mysql_query('
SHOW TABLE STATUS WHERE Data_free / Data_length > 0.1 AND Data_free > 102400
');
while($row = mysql_fetch_assoc($res)) {
mysql_query('OPTIMIZE TABLE ' . $row['Name']);
}
And that's all there is to it. You could then run this PHP code snippet within a full PHP script and run it via cron once per day.
Related posts:
- Optimize a table in MySQL from phpMyAdmin (Saturday, September 6th 2008)
- Optimize a table in MySQL from the command line interface (Thursday, September 4th 2008)
Recent posts:
- MySQL queries for article summaries part 2 of 2 (Tuesday, January 6th 2009)
- Aims for 2009 (Monday, January 5th 2009)
- Weekly Roundup - January 5th 2008 (Monday, January 5th 2009)
- MySQL queries for article summaries part 1 of 2 (Sunday, January 4th 2009)
- 2008 Summary of Posts (Saturday, January 3rd 2009)
- 2008 / 2009 overview (Friday, January 2nd 2009)
Subscribe to RSS Feed / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email and have my posts sent in a daily email.
Posts are made using the following schedule (although it may vary some weeks): Mondays & Fridays = PHP; Tuesdays & Saturdays = MySQL; Wednesdays & Sundays = Javascript/jQuery; Thursdays = HTML/CSS.
