How to speed up your mysql queries

Tagged:  

Ran into this while reading Ubuntu Linux Unleashed, 2008 Edition. It's a great book about linux mainly, but also has some basics about mysql, apache, php, pearl, python and some other goodies (definitely worth buying of you are a programmer and wanna get into linux).

At some point it had some tips on how to optimize queries in mysql:

. Select as little data as possible. Rather than SELECT *, select only the fields you need.
. If you only need a few rows, use LIMIT to select the number you need.
. Declare fields as NOT NULL when creating tables to save space and increase speed.
. Provide default values for fields, and use them where you can.
. Be very careful with table joins because they are the easiest way to write inefficient
queries.
. If you must use joins, be sure you join on fields that are indexed. They should also
preferably be integer fields, as these are faster than strings for comparisons.
. Find and fix slow queries. Add log-long-format and log-slow-queries =
/var/log/slow-queries.log to your /etc/my.cnf file, under [mysqld], and MySQL
will tell you the queries that took a long time to complete.
. Use OPTIMIZE TABLE tablename to defragment tables and refresh the indexes.

You can also search for optimization on mysql.com and see what comes up. All the mysql manuals (for different versions) have a chapter about this.