[Database] MySQL secondary index

MySQL secondary index

I. Introduction

1. Need to understand MySQL indexes.
2. In MySQL, when a table is created, a clustered index is created by default as the primary key. The B+ tree organizes all the data in the table, that is, the data is the index primary key. So in InnoDB, the primary key index is also called a clustered index , The leaf node of the index stores the entire row of data. All indexes except the clustered index are called secondary indexes, and the content of the leaf nodes of the secondary index is the value of the primary key.

Second, create a secondary index

Create a secondary index:

CREATE INDEX [index name] ON [table name]([column name]);

or

ALTER TABLE [table name] ADD INDEX [index name]([column name]);

In MySQL, the CREATE INDEX operation is mapped to ALTER TABLE ADD_INDEX.

3. Secondary index format

For example, create the following table:

CREATE TABLE users(
    id INT NOT NULL, 
    name VARCHAR(20) NOT NULL,
    age INT NOT NULL, 
    PRIMARY KEY(id) 
    );

Create a new secondary index with age field:

ALTER TABLE users ADD INDEX index_age(age);

MySQL will create a clustered index of the primary key id and a secondary index of age:
Insert picture description here

In MySQL, the leaf node of the primary key index stores the entire row of data, and the content of the secondary index leaf node is the value of the primary key.

Fourth, the retrieval process of the secondary index

In the MySQL query process, the SQL optimizer will select the appropriate index for retrieval. In the process of using the secondary index, because the secondary index does not store all the data, if the secondary index meets the query requirements (in general, such as Only check the id and current column attributes), then return directly, which is a covering index, otherwise, you need to go back to the table to query the primary key index (clustered index).

Such as executing

SELECT * FROM users WHERE age=35;

Need to return to the table:
Insert picture description here

Use EXPLAIN to view the execution plan and you can see that the index used is the index_age we created earlier:
Insert picture description here

Therefore: the secondary index is the mapping between the specified field and the primary key. The smaller the primary key length, the smaller the leaf node of the ordinary index, and the smaller the space occupied by the secondary index. Therefore, avoid using too long fields as the primary key.

Attachment: The above knowledge is derived from simplifying the monthly report of the database kernel-2020/01 . I hope it helps you get started.

Guess you like

Origin blog.csdn.net/thesprit/article/details/112989674