10.3.1 How MySQL Uses Indexes (original) (raw)

10.3.1 How MySQL Uses Indexes

Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. This is much faster than reading every row sequentially.

Most MySQL indexes (PRIMARY KEY,UNIQUE, INDEX, andFULLTEXT) are stored inB-trees. Exceptions: Indexes on spatial data types use R-trees; MEMORY tables also support hash indexes; InnoDB uses inverted lists for FULLTEXT indexes.

In general, indexes are used as described in the following discussion. Characteristics specific to hash indexes (as used inMEMORY tables) are described inSection 10.3.9, “Comparison of B-Tree and Hash Indexes”.

MySQL uses indexes for these operations:

SELECT MIN(key_part2),MAX(key_part2)  
  FROM tbl_name WHERE key_part1=10;  
SELECT key_part3 FROM tbl_name  
  WHERE key_part1=1  

Indexes are less important for queries on small tables, or big tables where report queries process most or all of the rows. When a query needs to access most of the rows, reading sequentially is faster than working through an index. Sequential reads minimize disk seeks, even if not all the rows are needed for the query. See Section 10.2.1.23, “Avoiding Full Table Scans” for details.