MySQL Optimization Tutorial

A while back I wrote a little introductory MySQL Administration tutorial. The tutorial had your basic information about starting the database server and creating databases. Now, I would like to jot down some commands that are useful when trying to optimize a SQL query on MySQL.

The first thing you need is to have a normalized database. This tutorial assumed you do and will not go into how to normalized you database schema.

In my limited experience with MySQL optimization techniques I have found that the single most important thing you can do is to create indices for foreign key columns and other columns used in the where clause. Here is the command to create an index.


You list more than one column names to create an index for more than one column. To list all the indices on a table you can execute the following command.

And finally, if you would like to delete a index you use the drop command as in the following SQL statement.

Again, as a general rule of thumb all foreign keys should be indexed. If you feel that the index did not help I recommend you use the explain command to view the execution plan of the database engine. The explain command probably deserves a tutorial of its own. The explain command will return a table detailing the execution plan and the most important column on that table is the type. If you have a value of ALL on that column your SQL statement will do a full table scan, which you should avoid. Here is how to use the explain command.

I also have found that after you delete a lot of rows for a particular table you should optimize it.

If you have inserted a great number of rows I would analyze the table with SQL similar to the following.

If this does not help, you can always throw more memory at the problem. MySQL also has a ton of start up options to control the size of the index cache and other startup parameters with performance issues.

Technorati Tags: , , , , , , , ,

Java 7: The Closure Debate »
« Mac OS X F11 Key
 
Related Posts
Recent Posts
 

3 Comments so far

  1. Sheeri on February 10th, 2007

    MySQL requires that foreign keys be indexed, so it’s not optional.

  2. Sheeri on February 10th, 2007

    (er, that is, when you’re using actual foreign key constraints, which you should do —

    ALTER tblname ADD FOREIGN KEY (fieldlist....) REFERENCES tbl2 (fieldlist....)
    
  3. TechKnow on February 12th, 2007

    @Sheeri - Thanks, I didn’t know that. For some reason I thought MySQL didn’t do much for foreign key constraints. Was that ever an issue in MySQL 3/4? It seems I have to read the latest documentation.

Leave a reply