primary key index sort invalid

Environment: MySQL8

There is a user information table user_info, and the DDL for creating the table is as follows:

CREATE TABLE `user_info` (
  `id` int(11) NOT NULL COMMENT '用户编号',
  `age` int(11) NOT NULL COMMENT '用户年龄',
  PRIMARY KEY (`id`),
  KEY `idx_age` (`age`) USING BTREE COMMENT '年龄索引'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

There are only two columns, the first column is the user number idas the primary key, and the second column is the user's age agewith a common index idx_age.
Now initialize a few rows of data:

INSERT INTO `user_info` (`id`,`age`) VALUES(1,1),(5,3),(7,8),(11,12);

Check all records:

Then insert a row of data into this table (6,1), and guess where this row of data will eventually be inserted?
Most people may think that it is inserted between (5,3)and (7,8), because if id=6, 5<6<7.
But looking at the results again, it was found that it was as expected, but inserted between (1,1)and (5,3):

it looks like the effect has agebecome the primary key, agesorted according to the default, or the primary key index sorting is invalid.

This is because in the underlying implementation of MySQL, user_infothere is a special way of handling such special tables. The special point of this user_infotable is that there are only two columns, one column is the primary key, and the other column also has an index.
At this time, the age column of the non-primary key is one 覆盖索引, because the index of age can find all fields.
MySQL internally believes that when accessing data, the efficiency of the covering index is higher than that of the primary key index , so the maintenance of the default sorting will be based on the covering index column first.
Check out the execution plan,

  • type=index, which means that only the index tree has been traversed;
  • key=idx_age, which means that the index is actually used;
  • Extra=Using index means that the covering index is effective, and the required data can be found in the index tree, avoiding the need to return to the table and scan the table data file.

Guess you like

Origin blog.csdn.net/songzehao/article/details/124069848