Each InnoDB
table has a special index called
the clustered index that stores row data. Typically, the clustered
index is synonymous with the primary key. To get the best
performance from queries, inserts, and other database operations,
it is important to understand how InnoDB
uses
the clustered index to optimize the common lookup and DML
operations.
When you define a
PRIMARY KEY
on a table,InnoDB
uses it as the clustered index. A primary key should be defined for each table. If there is no logical unique and non-null column or set of columns to use a the primary key, add an auto-increment column. Auto-increment column values are unique and are added automatically as new rows are inserted.If you do not define a
PRIMARY KEY
for a table,InnoDB
uses the firstUNIQUE
index with all key columns defined asNOT NULL
as the clustered index.If a table has no
PRIMARY KEY
or suitableUNIQUE
index,InnoDB
generates a hidden clustered index namedGEN_CLUST_INDEX
on a synthetic column that contains row ID values. The rows are ordered by the row ID thatInnoDB
assigns. The row ID is a 6-byte field that increases monotonically as new rows are inserted. Thus, the rows ordered by the row ID are physically in order of insertion.
Accessing a row through the clustered index is fast because the index search leads directly to the page that contains the row data. If a table is large, the clustered index architecture often saves a disk I/O operation when compared to storage organizations that store row data using a different page from the index record.
Indexes other than the clustered index are known as secondary
indexes. In InnoDB
, each record in a
secondary index contains the primary key columns for the row, as
well as the columns specified for the secondary index.
InnoDB
uses this primary key value to search
for the row in the clustered index.
If the primary key is long, the secondary indexes use more space, so it is advantageous to have a short primary key.
For guidelines to take advantage of InnoDB
clustered and secondary indexes, see
Section 8.3, “Optimization and Indexes”.