How to optimize MySQL database with a command

When you delete large portions for data from your MySQL table, the database becomes more fragmented. It is always a good idea to re-optimize your MySQL database especially if you have a lot of varying characters (VARCHAR). Here’s the command to optimize just one table:

[code lang=”sql”]OPTIMIZE TABLE foo[/code]


But I am looking for a more command line solution and here it is:

[code lang=”bash”]mysqlcheck -op database_name[/code]

The ‘o’ refers to optimize. And the ‘p’ is the option for password requirement. You’ll be prompted for the password.

If you’re logged in as user ‘john’ in your SSH, the MySQL username will be ‘john’. If that’s not what you want, use option ‘u’ like this:

[code lang=”bash”]mysqlcheck -op -u user_name database_name[/code]

And to optimize all databases:

[code lang=”bash”]mysqlcheck -op -u user_name –all-databases[/code]

You can also use option ‘r’ to repair.

Note that the optimization only works for MyISAM, InnoDB, and ARCHIVE tables.