views:

58

answers:

3

The explain command with the query:

explain SELECT * FROM leituras 
WHERE categorias_id=75 AND 
textos_id=190304 AND 
cookie='3f203349ce5ad3c67770ebc882927646' AND 
endereco_ip='127.0.0.1' 
LIMIT 1

The result:

id     select_type     table     type     possible_keys     key     key_len     ref     rows     Extra       
1      SIMPLE          leituras  ALL      (null)            (null)  (null)      (null)  1022597  Using where 

Will it make any difference adding some keys on the table? Even that the query will always return only one row.

+2  A: 

It still has to do a linear search over the table until it finds that one row. So adding indexes could noticeably improve performance.

Matthew Flaschen
+3  A: 

In answer to your question, yes. You should add indexes where necessary (thanks @Col.Shrapnel) on the columns that appear in your WHERE clause - in this case, categorias_id, textos_id, cookie, and endereco_ip.

If you always perform a query using the same 3 columns in the WHERE clause, it may be beneficial to add an index which comprises the 3 columns in one go, rather than adding individual indexes.

richsage
not "where possible" but where necessary
Col. Shrapnel
@Col.Shrapnel - yes, good point :-)
richsage
+1  A: 

Yes, indexes are even more important when you want to return only one row.

If you are returning half of the rows and your database system has to scan the entire table, you're still at 50% efficiency.

However, if you want to return just one row, and your database system has to scan 1022597 rows to find your row, your efficiency is minuscule.

LIMIT 1 does offer some efficiency in that it stops as soon as it finds the first matching row, but it obviously has to scan an enormous number of records to find that first row.

Adding an index for each of the columns in your WHERE clause allows your database system to avoid scanning rows that don't match your criteria. With adequate indexes, you'll see that the rows column in the explain will get closer to the actual number of returned rows.

Using a compound index that covers all four of the columns in your WHERE clause allows even better performance and less scanning, as the index will provide full coverage. Compound indexes do use a lot of memory and negatively affect insert performance, so you might only want to add a compound index if a large percentage of your queries repeatedly do a look up on the same columns, or if you rarely insert records, or it's just that important to you for that particular query to be fast.

Another way to improve performance is to return only the columns that you need rather than using SELECT *. If you had a compound index on those four columns, and you returned only those four columns, your database system wouldn't need to hit your records at all. The database system could get everything it needed right from the indexes.

Marcus Adams
Thank you man! I'll add the indexes to improve the query performance.
Ricardo