11. Basic use of index

1. Introduction
Index is a special data structure, similar to the catalog of books, it can greatly improve the query efficiency of the database. If there is no index, all records in the table must be scanned to find the records that meet the conditions when querying data. This kind of full table scan query efficiency is very low.

2. Type

Index type description
Normal index The most basic index, without any restrictions, only speeds up queries
Unique index The value of the index column must be unique, but null values ​​are allowed
Primary key index A special unique index that does not allow null values. Generally, the primary key index is automatically created when the table is built
Compound index An index on two or more columns is called a compound index
Full-text index Word segmentation index for text content

3. Use

#创建普通索引
create index indexName on tableName(field(length));

#创建唯一索引
create unique index indexName on tableName(field(length));

#创建复合索引
create index indexName on tableName(field1, field2,,fieldN);

#删除索引
drop index indexName on tableName;

#查看索引
show index from tableName;

4. Composite index leading column characteristics
In MySQL, if a composite index (name, salary, dept) is created, it is equivalent to creating three indexes (name, salary, dept), (name, salary) and (name). This is called the leading column feature of the composite index, so when creating a composite index, the columns most commonly used as query conditions should be placed on the leftmost side, and then descended in order.

#未使用索引
select * from employee where salary = 8800;
select * from employee where dept = '部门A';
select * from employee where salary = 8800 and dept = '部门A';

#使用索引
select * from employee where name = 'liufeng';
select * from employee where name = 'liufeng' and salary = 8800;
select * from employee where name = 'liufeng' and salary = 8800 and dept = '部门A';

5. Covering index
Covering index is also called index coverage, that is, select data columns can only be obtained from the index, without reading the data rows, that is, only by scanning the index to get the query results. When a query uses a covering index, you can see "Using index" in the extra column of the query analyzer explain.

Using a covering index, you only need to retrieve the data you need from the index, instead of scanning the data table.
The volume of the index is often much smaller than that of the data table, so only reading the index will be faster and will greatly reduce the amount of data access.
MySQL's query optimizer will determine before executing the query whether there is an index that can cover all query columns.
Not all types of indexes can be used as covering indexes, covering indexes must store the value of the index column. Such as hash index, spatial index, full-text index, etc. do not really store the value of the index column.

Guess you like

Origin blog.csdn.net/Jgx1214/article/details/107496136