search
HomeDatabaseMysql TutorialHow to use clustered index, auxiliary index, covering index and joint index in mysql

Clustered Index

The clustered index constructs a B-tree based on the primary key of each table, and the row record data of the entire table is stored in the leaf nodes.

For example, let’s intuitively feel the clustered index.

Create table t, and artificially allow each page to store only two row records (I don’t know how to artificially control only two row records per page):

How to use clustered index, auxiliary index, covering index and joint index in mysql

Finally, the author of "MySQL Technology Insider" obtained the rough structure of this clustered index tree through analysis tools as follows:

How to use clustered index, auxiliary index, covering index and joint index in mysql

The leaf nodes of a clustered index are referred to as data pages, each of which is linked by a doubly linked list, and the data pages are arranged in the order of primary keys..

As shown in the figure, each data page stores a complete row record, while in the index page of the non-data page, only the key value and the offset pointing to the data page are stored. Not a complete line record.

If a primary key is defined, InnoDB will automatically use the primary key to create a clustered index. When no primary key is defined, InnoDB will choose a unique and non-empty index to serve as the primary key. InnoDB will implicitly define a primary key as a clustered index if there is no unique non-null index.

Secondary Index

Auxiliary index, also called non-clustered index. Compared with the clustered index, the leaf nodes do not contain all the data of the row records. In addition to the key value, the leaf node's index row also contains a bookmark (bookmark), which is used to tell InnoDB where to find the row data corresponding to the index.

Let’s use the example in "MySQL Technology Insider" to intuitively feel what the auxiliary index looks like.

Still taking the above table t as an example, create a non-clustered index on column c:

How to use clustered index, auxiliary index, covering index and joint index in mysql

Then the author obtains the auxiliary index and clustered index through analysis work Relationship diagram:

How to use clustered index, auxiliary index, covering index and joint index in mysql

You can see that the leaf node of the auxiliary index idx_c contains the value of column c and the value of the primary key.

For example, assume that the value of Key is 0x7ffffffff, where the binary representation of 7 is 0111 and 0 is a negative number. The actual integer value should be inverted plus 1, so the result is -1, and this is the value in column c. The primary key value is a positive number 1, represented by the pointer value 80000001, where 8 bits represent the binary number 1000.

Covering index

Using the InnoDB storage engine, you can cover the index through the auxiliary index and obtain the query records directly without querying the records in the clustered index.

What are the benefits of using covering index?

  • Can reduce a large number of IO operations

We know from the above figure that if you want to query fields that are not included in the auxiliary index, you must first traverse Auxiliary index, and then traverse the clustered index. If the field value to be queried exists in the auxiliary index, there is no need to check the clustered index, which will obviously reduce IO operations.

For example, in the picture above, the following sql can directly use the auxiliary index,

select a from where c = -2;
  • It is helpful for statistics

Assume that there is As shown in the following table:

  CREATE TABLE `student` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) NOT NULL,
  `age` varchar(255) NOT NULL,
  `school` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_name` (`name`),
  KEY `idx_school_age` (`school`,`age`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

If executed on this table:

select count(*) from student

How will the optimizer handle it?

The optimizer will choose the auxiliary index for statistics, because although results can be obtained by traversing both the clustered index and the auxiliary index, the size of the auxiliary index is much smaller than the clustered index. Execute the explain command:

How to use clustered index, auxiliary index, covering index and joint index in mysql

key and Extra show that the auxiliary index idx_name is used.

Also, assume that the following sql is executed:

select * from student where age > 10 and age < 15

Because the field order of the joint index idx_school_age is first school and then age, the conditional query is based on age, usually without indexing:

How to use clustered index, auxiliary index, covering index and joint index in mysql

However, if the conditions remain unchanged, querying all fields is changed to querying the number of entries:

select count(*) from student where age > 10 and age < 15

The optimizer will choose this joint index:

How to use clustered index, auxiliary index, covering index and joint index in mysql

Joint index

Joint index refers to indexing multiple columns on the table.

The following is an example of creating a joint index idx_a_b:

How to use clustered index, auxiliary index, covering index and joint index in mysql

Internal structure of the joint index:

How to use clustered index, auxiliary index, covering index and joint index in mysql

联合索引也是一棵B+树,其键值数量大于等于2。键值都是排序的,通过叶子节点可以逻辑上顺序的读出所有数据。数据(1,1)(1,2)(2,1)(2,4)(3,1)(3,2)是按照(a,b)先比较a再比较b的顺序排列。

基于上面的结构,对于以下查询显然是可以使用(a,b)这个联合索引的:

select * from table where a=xxx and b=xxx ;

select * from table where a=xxx;

但是对于下面的sql是不能使用这个联合索引的,因为叶子节点的b值,1,2,1,4,1,2显然不是排序的。

select * from table where b=xxx

联合索引的第二个好处是对第二个键值已经做了排序。举个例子:

create table buy_log(
    userid int not null,
    buy_date DATE
)ENGINE=InnoDB;

insert into buy_log values(1, &#39;2009-01-01&#39;);
insert into buy_log values(2, &#39;2009-02-01&#39;);

alter table buy_log add key(userid);
alter table buy_log add key(userid, buy_date);

当执行

select * from buy_log where user_id = 2;

时,优化器会选择key(userid);但是当执行以下sql:

select * from buy_log where user_id = 2 order by buy_date desc;

时,优化器会选择key(userid, buy_date),因为buy_date是在userid排序的基础上做的排序。

如果把key(userid,buy_date)删除掉,再执行:

select * from buy_log where user_id = 2 order by buy_date desc;

优化器会选择key(userid),但是对查询出来的结果会进行一次filesort,即按照buy_date重新排下序。所以联合索引的好处在于可以避免filesort排序。

The above is the detailed content of How to use clustered index, auxiliary index, covering index and joint index in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools