Enterprise Linux Log

Apr 10 2007   9:53AM GMT

How not to manage a MySQL query

ITKE ITKE Profile: ITKE

Poorly written queries will run slowly in MySQL. There’s really no way around it, but a slew of posts over at Digg.com are trying anyway. One blogger named Mike that I found today takes them all to task with a few tips on the proper way to handle this sticky SQL situation:

Properly index your tables

If you do a lot of lookups using a particular column of a table, or if you join on a column, that column should be indexed. Moreover, if all of the data that you are retrieving is available in the index (e.g. you’re using a multi-column index) then MySQL can avoid looking at the table altogether and execute your query using just the index.
Avoid superfluous queries

Don’t do this:

$result = query_db(‘select * from table1′);

for each $result as $row
$array[] = query_db(‘select * from table2 where column = ‘.$row[‘id’]);
endforeach;

Do this:

$result = query_db(‘select table2.* from ‘
.’table1, table2 where table1.id=table2.column’);

Look for bottlenecks

Don’t waste time optimizing queries that aren’t bottlenecks in your application. Find the low hanging fruit and correct those problems first.

Learn SQL

This is the most important tip. SQL optimization really has to be done on a case by case basis, and you can’t do it unless you have a good understanding of the language and how you can use it to your advantage. You need to understand things like subqueries, grouping, left joins vs. right joins vs. full joins, etc. There is no free lunch.

Lunch… hmm. What time is it? MySQL queries make me hungry — but only if they’re well written!

Also, are you new to MySQL? Check out SearchEnterpriseLinux.com’s recent technical tip on Getting Started with MySQL.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: