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?

the
  • 21,007
  • 11
  • 68
  • 101
Wienczny
  • 3,958
  • 4
  • 30
  • 35

3 Answers3

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;
Yes Barry
  • 9,514
  • 5
  • 50
  • 69
Max Bube
  • 406
  • 4
  • 3
  • 9
    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; – El Yobo May 26 '10 at 13:11
  • You need some backticks cat-ed in there around table_schema and table_name, otherwise i owe you a beer, many thanks. – Question Mark Jan 04 '14 at 02:11
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.

bensiu
  • 24,660
  • 56
  • 77
  • 117
0

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

Richard Dev
  • 1,110
  • 7
  • 21