Mysql OPTIMIZE TABLE for all fragmented tables
Asked Answered
S

3

17

I'd like to OPTIMIZE all currently fragmented tables. These tables should have information_schema.DATA_FREE > 0.

Is it possible to optimize all tables with this property in one command in SQL or will I have to write external code to do this?

Succession answered 23/6, 2009 at 11:1 Comment(0)
A
39

You can do something like this:

SELECT concat("OPTIMIZE TABLE ", table_schema,".",table_name,";")
FROM tables
WHERE DATA_FREE > 0
INTO OUTFILE '/tmp/optimize.sql';
SOURCE '/tmp/optimize.sql';

Alternatively, if the first one fails, try:

SELECT concat("OPTIMIZE TABLE ", table_schema,".",table_name,";")
FROM information_schema.tables
WHERE DATA_FREE > 0
INTO OUTFILE '/tmp/optimize.sql';
SOURCE /tmp/optimize.sql;
Azucenaazure answered 23/6, 2009 at 15:15 Comment(2)
Slight changes required to work for me, but great approach. SELECT concat("OPTIMIZE TABLE ", table_schema,".",table_name,";") FROM information_schema.tables WHERE DATA_FREE > 0 INTO OUTFILE '/tmp/optimize.sql'; SOURCE /tmp/optimize.sql;Wapiti
You need some backticks cat-ed in there around table_schema and table_name, otherwise i owe you a beer, many thanks.Sustentation
K
1

ok, this is an old post, but this is needed.

Phil Dufault http://www.dufault.info/blog/a-script-to-optimize-fragmented-tables-in-mysql/ has written a wonderfull script, that is on github: https://github.com/pdufault/mysqlfragfinder/blob/master/mysqlfragfinder.sh

vim mysqlfragfinder.sh
#copy paste from github
chmod +x ./mysqlfragfinder.sh
./mysqlfragfinder.sh --user root_username --password root_password

and that is all. Have been using it on a number of servers for a while now.

Knifeedged answered 9/4, 2012 at 9:44 Comment(0)
Y
1

I know there is a answer. But MySQL has this recommendation for INNODB DB's:

It can speed up index scans if you periodically perform a “null” ALTER TABLE operation, which causes MySQL to rebuild the table:

ALTER TABLE tbl_name ENGINE=INNODB

Found here http://dev.mysql.com/doc/refman/5.0/en/innodb-file-defragmenting.html

Yorgo answered 8/10, 2013 at 21:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.