[Interview] What is the difference between Mysql primary key index, ordinary index index and unique index?

foreword

In MySQL, the index is implemented at the storage engine layer, so there is no unified index standard. Since the InnoDB storage engine is the most widely used in the MySQL database, the following uses InnoDB as an example to analyze the index model .In InnoDB, tables are stored in the form of indexes according to the order of the primary key. InnoDB uses the B+ tree index model, so the data is stored in the B+ tree.

Indexes are used to quickly find records with specific values, and all MySQL indexes are stored in the form of B-trees. MySQL provides a variety of index types to choose from: common index, unique index, primary key index, full-text index, etc.

The following article will introduce the difference between the primary key index and the ordinary index, and I hope it will be helpful to you.

analyze

insert image description here

As can be seen from the figure, according to the content of the leaf nodes, the index type is divided into primary key index and non-primary key index.

  • The primary key index is also called a clustered index, and the leaf nodes store the entire row of data;
  • Non-primary key indexes are called secondary indexes, and the leaf nodes store the value of the primary key.
  • If you query based on the primary key, you only need to search the B+ tree of ID
  • If you query through a non-primary key index, you need to search the k index tree first, find the corresponding primary key, and then search the ID index tree again. This process is called returning to the table.

primary key index

  • The primary key index cannot be empty
  • The primary key index can be used as a foreign key
  • There can only be one primary key index in a table

normal index

  • An index created to speed up data access.
  • It is mostly based on fields that often appear in query conditions and fields that are often used for sorting.
  • Indexed data columns are allowed to contain duplicate values

unique index

Indexed data columns are not allowed to contain duplicate values

Summarize

The query of the non-primary key index needs to scan one more index tree, which is relatively inefficient.

  • Ordinary index is the most basic index type, without any restrictions, the value can be empty, only to speed up the query. Ordinary indexes can be repeated, and there can be multiple ordinary indexes in a table.

  • The primary key index is a special unique index. A table can only have one primary key, and no null values ​​are allowed; all values ​​of the index column can only appear once, that is, they must be unique. To put it simply: the primary key index is to speed up the query + the column value is unique (null is not allowed) + there is only one in the table.

Guess you like

Origin blog.csdn.net/u011397981/article/details/130034347