Search code examples
mysqloptimizationindexingexplain

The explain tells that the query is awful (it doesn't use a single key) but I'm using LIMIT 1. Is this a problem?


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.


Solution

  • 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.