Detailed explanation of the way MySQL creates indexes, index deletion, MySQL8.0 descending index

1. How to create an index

  • Method 1: Specify the index column when creating the table
  • Method 2: Create an index using ALTER TABLE
  • Method 3: Use CREATE TABLE to create an index

2. The way to view the index in the table

  • Method 1: Use the statement SHOW INDEX FROM table name;  statement to view the index in the table

like:

  • Method 2: Use the statement  SHOW CREATE TABLE STUDENT01;  statement to view the DDL statement of the table, you can explicitly see the index creation statement

like:

3. Specify the index column when creating the table

3.1. Implicit index creation

  • On fields declared with primary key constraints, unique constraints, and foreign key constraints, related indexes will be automatically added
--创建学生表01,指定ID为主键,此时会自动添加主键索引
CREATE TABLE STUDENT01(
	ID INT PRIMARY KEY AUTO_INCREMENT
	,NAME VARCHAR(20) UNIQUE 
	,AGE INT
)
  • Look at the index method 1 in the table:
--查看当前表的索引
SHOW INDEX FROM STUDENT01;

The index results are as follows:

  • Look at the index method 2 in the table:
SHOW CREATE TABLE STUDENT01;

The result is as follows:

  

Note: A foreign key constraint is a constraint between tables, not an index

Foreign key case:

--案例:
--创建TEACHER01表
CREATE TABLE TEACHER01(
	ID INT PRIMARY KEY AUTO_INCREMENT
	,NAME VARCHAR(20) UNIQUE 
)
--创建STUDENT18表,ID与TEACHER01表中的ID关联
CREATE TABLE STUDENT18(
	ID INT PRIMARY KEY AUTO_INCREMENT
	,NAME VARCHAR(20) UNIQUE 
	,AGE INT
	,CONSTRAINT STUDENT18_ID_FK FOREIGN KEY(ID) REFERENCES TEACHER01(ID)  --创建外键
)
--查看索引
SHOW INDEX FROM STUDENT18;

Index results in the STUDENT18 table:


3.2. Explicitly create indexes

Grammar format:

CREATE TABLE table name (

        column name 1 column type 1 ,

        column name 2 column type 2 ,

        ...

         [UNIQUE | FULLTEXT | SPATIAL] [INDEX | KEY] Index name (column name [index length]) [DESC | AESC]

)

  • UNIQUE, FULLTEXT, SPATIAL: Optional parameters, representing unique index, full-text index, and spatial index respectively
  • INDEX and KEY are synonyms: both have the same function and are used to specify the creation of an index
  • Index name: optional parameter, if omitted, MySQL uses the column name as the index name by default
  • Index length: optional parameter, only string type fields can specify the index length
  • ASC/DESC: Specify whether the index value stores the values ​​in descending or ascending order
create normal index
--创建学生表02,指定NAME为普通索引
CREATE TABLE STUDENT02(
	ID INT
	,NAME VARCHAR(20)
	,AGE INT
	,INDEX idx_name(name)
)
--查看索引
SHOW INDEX FROM STUDENT02;

The index query results are as follows:

Create a unique index (multiple null values ​​can be added)
--创建学生表03,指定ID为唯一索引
CREATE TABLE STUDENT03(
	ID INT
	,NAME VARCHAR(20)
	,AGE INT
	,UNIQUE INDEX idx_name(ID)
)

Test unique index:

--给STUDENT03表插入3条数据
INSERT INTO STUDENT03(id,name,age)
VALUES(1,'张三',18);
INSERT INTO STUDENT03(id,name,age)
VALUES(null,'张三',18);
INSERT INTO STUDENT03(id,name,age)
VALUES(null,'张三',18);

--查看所有数据
SELECT * FROM STUDENT03;

The result is as follows:

 Summary: A unique index cannot repeatedly insert the same data, but multiple null values ​​can be added

Create primary key index
  • The primary key index is created through the primary key constraint, which is the way to create the index implicitly

Drop the primary key index:

ALTER TABLE 表名 DROP PRIMARY KEY;

Note: When the primary key is auto-increment, you need to delete the auto-increment first, and then delete the primary key

Create a joint index
--创建学生表04,指定NAME、AGE和SCORE为联合索引
CREATE TABLE STUDENT04(
	ID INT
	,NAME VARCHAR(20)
	,AGE INT
	,SCORE decimal
	,INDEX idx_name_age(NAME,AGE,SCORE)
);
--查看索引
SHOW INDEX FROM STUDENT04;

The result is as follows:

Notice:

  • Since the order of the fields is NAME, AGE, SCORE when the index is created, the order of building the B+ tree is also arranged first by NAME, then by AGE, and finally by SCORE
  • Leftmost prefix principle: If you want to use the joint index, if there is no leftmost field name in the where condition, then the index will fail

We can use the keyword EXPLAIN test:

  • Test 1: All fields in the joint index are included in the where condition
--EXPLAIN 测试索引,where条件中使用了NAME,AGE,SCORE
EXPLAIN 
SELECT 
	* 
FROM STUDENT04 
WHERE
	NAME = '张三'
	AND AGE = 18
	AND SCORE = 85

The result is as follows: The above SQL statement uses the index

  • Test 2: The intermediate field AGE in the joint index is not included in the where condition
--EXPLAIN 测试索引,where条件中使用了NAME,SCORE,没有使用中间的字段AGE
EXPLAIN 
SELECT 
	* 
FROM STUDENT04 
WHERE
	NAME = '张三'
	AND SCORE = 85

The result is as follows: The above SQL statement uses the index

  • Test 3: The where condition does not include the leftmost field name in the joint index
EXPLAIN 
SELECT 
	* 
FROM STUDENT04 
WHERE
	AGE = 18
	AND SCORE = 85

The result is as follows: The index of the above SQL statement is invalid

  • Test 4: Create a unique index for the leftmost field name, and test whether to use a single-column index or a joint index

Note: This test must ensure that data exists in the table, otherwise the effect cannot be viewed!

--给STUDENT04表插入3条数据
INSERT INTO STUDENT04(id,name,age,score)
VALUES(1,'张三',18,85);

INSERT INTO STUDENT04(id,name,age,score)
VALUES(1,'李四',18,85);

INSERT INTO STUDENT04(id,name,age,score)
VALUES(1,'王五',18,85);

--测试索引执行情况
EXPLAIN 
SELECT 
	* 
FROM STUDENT04 
WHERE
	NAME = '张三'
	AND AGE = 18
	AND SCORE = 85

The result is as follows: The SQL statement uses a unique index instead of a joint index

Combined Index Usage Summary
  • Follow the leftmost prefix principle: when the leftmost field of the joint index is not used in the where condition, the index will fail 

According to the principle of B+ tree establishment: the data records in the node are sorted according to the leftmost field first, and then sorted according to the order of other fields in the index. Therefore, if the leftmost field is not used as a condition in where, Then the initial sorting (entry) of the data records of the B+ tree node is not used, and the fields sorted later will not take effect, resulting in index failure

  • The order of the fields in the where condition does not affect the joint index
  • In the where condition, as long as the leftmost field is used, the joint index will take effect
  • When a table has multiple indexes to go, which index to go will be selected according to the query cost of the optimizer

4. After the table is created, use ALTER TABLE to add indexes

grammar:

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

  • Index name can be omitted
  • [Index type]: can be omitted, omission is a normal index, if the index type is specified, then INDEX can also be omitted

like:

CREATE TABLE STUDENT05(
	ID INT
	,NAME VARCHAR(20) 
	,AGE INT
	,SCORE decimal
);

--给STUDENT05表SCORE字段创建普通索引
ALTER TABLE STUDENT05 ADD INDEX (score);
--给STUDENT05表NAME字段创建唯一索引
ALTER TABLE STUDENT05 ADD UNIQUE IDX_NAME(NAME);

--给STUDENT05表NAME,AGE,SCORE字段创建联合索引
ALTER TABLE STUDENT05 ADD INDEX IDX_NAME_AGE_SCORE(NAME,AGE,SCORE);

5. After the table is created, use CREATE INDEX to add the index

grammar:

CREATE [index type] INDEX index name ON table name (field name);

  • Index type can be omitted
  • Index name cannot be omitted
  • The INDEX keyword cannot be omitted

like:

CREATE TABLE STUDENT06(
	ID INT
	,NAME VARCHAR(20) 
	,AGE INT
	,SCORE decimal
);

--给STUDENT06表SCORE字段创建普通索引
CREATE INDEX idx_score ON STUDENT06(SCORE);

--给STUDENT06表NAME字段创建唯一索引
CREATE UNIQUE INDEX idx_name ON STUDENT06(NAME);

--给STUDENT05表NAME,AGE,SCORE字段创建联合索引
CREATE UNIQUE INDEX IDX_NAME_AGE_SCORE ON STUDENT06(NAME,AGE,SCORE);

6. The difference between the ALTER TABLE method and the CREATE INDEX method

  • When creating a non-ordinary index in ALTER mode, the INDEX keyword can be omitted, but in CREATE mode INDEX cannot be omitted
  • The ALTER method does not need to specify the index name, and the field name is used as the index name by default, while the C REATE method cannot omit the index name

7. Delete the index

Index deletion scenario:

  • The number of table indexes is large. When a large number of additions, deletions and changes are required, the indexes can be deleted first, and then the data can be deleted.

Method 1:

ALTER TABLE table name DROP index name;

Method 2:

DROP INDEX index name ON table name;

Notice:

  • When the field of a single-column index is deleted, the index will be automatically deleted
  • When a field of the joint index is deleted, the joint index will automatically delete the field

8. Descending index

  • Indexes store key values ​​in ascending order by default
  • On MySQL syntax. The descending index syntax has been supported since version 4.0, but in fact the DESC definition is ignored
  • MySQL8.0 version began to really support descending index (only supported by InnoDB)

The ascending index created by MySQL before 8.0 is still used for reverse scanning, which greatly reduces the efficiency of the database.

In some scenarios, descending indexes are of great significance. For example:

         If a query needs to sort multiple columns, and the order requirements are inconsistent, then using a descending index will avoid the database from using additional file sorting operations, thereby improving performance.

case:

1> In MySQL8, when creating a table, create a joint index, and specify a in ascending order and b in descending order in the index

CREATE TABLE STUDENT07(
	a INT
	,b INT  
	,INDEX IDX_A_B(a ASC,b DESC)
);

2> Insert 799 pieces of simulated data using stored procedures

-- 创建存储过程
DELIMITER //
CREATE PROCEDURE STUDENT07_insert() 
BEGIN
	DECLARE i INT DEFAULT 1;
	WHILE i<800
	DO
		insert into STUDENT07 select rand()*80000,rand()*80000; 
		SET i=i+1;
	END WHILE;
	commit; 
END //
DELIMITER ;

-- 调用存储过程
CALL STUDENT07_insert();

3> Test using descending index

EXPLAIN SELECT * FROM STUDENT07 ORDER BY a,b DESC LIMIT 5;

Result: It proves that the sorting uses the index, and the performance is good

 4> Delete the above joint index, create a new joint index, a is ascending, b is also ascending (simulating versions below MySQL8)

-- 删除原来的索引
DROP INDEX IDX_A_B ON STUDENT07;

-- 创建新的联合索引,a升序,b也升序(模拟MySQL8以下的版本)
CREATE INDEX IDX_A_B ON STUDENT07(a,b);	--默认就是升序的

5> test does not use descending index

EXPLAIN SELECT * FROM STUDENT07 ORDER BY a,b DESC LIMIT 5;

Result:  used filesort (filesort, bad performance)

​​​​​​​

Guess you like

Origin blog.csdn.net/weixin_42675423/article/details/131703389