当前位置:网站首页>How to understand MySQL indexes?
How to understand MySQL indexes?
2022-06-29 03:20:00 【Dark horse programmer official】
One 、 What is index
The index is defined as : Indexes (index) Help MySQL Efficient access to data data structure ( Orderly ). Out of data , The database system also maintains a data structure that satisfies a specific search algorithm , These data structures are referenced in some way ( Point to ) data , In this way, advanced search algorithms can be implemented on these data structures , This data structure is the index .
The process of sorting data is called Indexes
Let's check according to the index , Increase of efficiency

MySQL The establishment of index for MySQL It is very important to run efficiently , The index can be greatly improved MySQL Retrieval speed of .
If the index is properly designed and used MySQL It's a Lamborghini , So there's no index designed and used MySQL It's a human powered tricycle .

Two 、MySQL Index classification
markdown * Primary key ( constraint ) Indexes Primary key constraint + Improve query efficiency
- only ( constraint ) Indexes Unique constraint + Improve query efficiency
- General index Only improve query efficiency
- Combine ( union ) Indexes Multiple fields form an index name age
- hash Indexes according to key-value Very efficient
- Full-text index By looking for keywords in the text , Similar to search engines
explain : When we create a table, we specify gradual and unique constraints , Then it is equivalent to adding primary keys and unique indexes to the fields of the table .
3、 ... and 、MySQL Index Syntax
3.1 Create index
① Directly create... On the fields of the existing table 【 understand 】
-- Create a normal index
create index Index name on Table name ( Field );
-- Create unique index
create unique index Index name on Table name ( Field );
-- Create a normal Composite Index
create index Index name on Table name ( Field 1, Field 2,..);
-- Create a unique composite index
create unique index Index name on Table name ( Field 1, Field 2,..);
explain :
- If you create multiple indexes in the same table , Make sure that the index name cannot be repeated .
- The above method of creating index is troublesome , You also need to specify the index name .
- You cannot add a primary key index in the above way .
【 Ready to create table SQL sentence 】
create database day04;
use day04;
-- Create student table
CREATE TABLE student(
id INT,
name VARCHAR(32),
telephone VARCHAR(11)
);
【 Index the fields of the above table 】
1. to name Field to set the general index
CREATE INDEX name_idx ON student(name);
2. to telephone Field sets a unique index
CREATE UNIQUE INDEX telephone_uni_idx ON student(telephone);
After setting, you can view the set index through graphical tools :


② Specify when modifying a table on a field of an existing table 【 understand 】
-- Add a primary key , This means that the index value must be unique , And cannot be NULL
alter table Table name add primary key( Field ); -- Default index name :primary
-- Add unique index ( except NULL Outside ,NULL There may be many times )
alter table Table name add unique( Field ); -- Default index name : Field name
-- Add a normal index , Index values can appear multiple times .
alter table Table name add index( Field ); -- Default index name : Field name
【 Prepared to create a table SQL sentence 】
-- Create student table
CREATE TABLE student2(
id INT,
name VARCHAR(32),
telephone VARCHAR(11)
);
【 Index the fields of the above table 】
1. Appoint id Index for primary key
ALTER TABLE student2 ADD PRIMARY KEY(id);
2. Appoint name For general index
ALTER TABLE student2 ADD INDEX(name);
3. Appoint telephone For unique index
ALTER TABLE student2 ADD UNIQUE(telephone);
After setting, you can view the set index through graphical tools :

③ Specify... When creating a table 【 master 】
-- Create student table
CREATE TABLE student3(
id INT PRIMARY KEY AUTO_INCREMENT, -- primary key
name VARCHAR(32),
telephone VARCHAR(11) UNIQUE, -- unique index
sex VARCHAR(5),
birthday DATE,
INDEX(name) -- General index
);

3.2 Look at the index
show index from Table name ;
【 see student3 Table index information 】
show index from student3;
result :

3.3 Delete index
- grammar
【 grammar 1】 Delete directly
-- Delete directly
drop index Index name on Table name ;
【 grammar 2】 Delete when modifying table
-- Delete when modifying table
alter table Table name drop index Index name ;
- practice
(1) Delete student Tabular name General index
DROP INDEX name_idx ON student;
(2) Delete student Tabular telephone unique index
ALTER TABLE student DROP INDEX telephone_uni_idx;
Four 、 Demonstration of index effect of tens of millions of table records
Use the previously created user Test tens of millions of data in the data sheet . Be careful user There is no index in the table .

【1. Let's test the query without index 】
-- 1. Appoint id Inquire about
select * from user where id = 8888888;
-- 2. Appoint username Accurate query
select * from user where username = 'jack1234567';

【2. To give the 2 Add an index to a field 】
explain : When adding an index to a field of a table , The bottom layer carries out association and combination through sorting . So it takes some time , And the index will also take up hard disk space . So we need to be careful when using the index .
Before adding an index , The amount of data in hard disk space :

Add indexes to the following fields as follows :
-- Appoint id Index for primary key
ALTER TABLE USER ADD PRIMARY KEY(id);
-- Appoint username For general index
ALTER TABLE USER ADD INDEX(username);

After adding the index , The amount of data in hard disk space :

If you add an index to more than one , Then the amount of hard disk space will increase . If the table is complex , If you add more indexes , There may be several more than before G It's also possible .
【3. Then test the query with index 】
-- 1. Appoint id Inquire about
select * from user where id = 8888888;
-- 2. Appoint username Accurate query
select * from user where username = 'jack1234567';

explain : From the above results, we can see that with the index , The query speed is dozens of times faster than before . Fly fast .
5、 ... and 、 Advantages and disadvantages of index
advantage
1) It's like a catalog index of books , Improve the efficiency of data retrieval , Reduce the IO cost .
2) At the bottom of the index is sorting , Sort data through index columns , Reduce the cost of sorting data , Reduce CPU Consumption of .
Inferiority
- In the process of database establishment , It takes more time to build and maintain the index , Especially with the increase of the total amount of data , The time spent will continue to increase .
- The index created in the database needs to occupy a certain amount of physical storage space , This includes the data space occupied by the data table and the physical space occupied by each index created .
- When modifying the data in the table , For example, add it 、 When deleting or modifying , Indexes also need to be dynamically maintained , This brings some trouble to the maintenance speed of the database .
6、 ... and 、 Follow up learning
What about indexing , also Learning data structures > Clustered index and non clustered index >hash Indexes > Overlay index > The principle of index creation > Avoid index invalidation > Optimization scheme for batch data paging query, etc Content .
There are also some high-frequency interview questions
【1】Hash Index and B+ What's the difference or advantage of tree ownership ?
【2】 What happens when an index is created for the column but not used in the query ( Index failure )?
【3】 You know, mysql What are the indexes ?
【4】 Is the index created used in ? Or how can we know why this statement runs slowly ?
【5】 What is a federated index ? Why should we pay attention to the order in the union index ?
【6】 Will non clustered index return to table query ?
边栏推荐
- MATALB signal processing - signal transformation (7)
- 图扑软件智慧能源一体化管控平台
- MATALB signal processing - signal transformation (6)
- Tortoise does not display a green Icon
- How to add the live video function to the website built by your own live video software (build a live video website)
- 初探元宇宙存储,数据存储市场下一个爆点?
- 无法定位程序输入点 [email protected]
- priority_ Understanding of queue
- Synchronous real-time data of Jerry's watch [chapter]
- Yyds dry inventory everything a primary developer should know about activity
猜你喜欢

Etcd tutorial - Chapter 6 etcd core API V3

逆序对对数计算,顺序对对数计算——归并排序

1110: nearest common ancestor (function topic)

Overview of PMP project management
![[flutter topic] 66 diagram basic constraints box (I) yyds dry goods inventory](/img/8b/55a43383e1cb6b37231dba980c7b11.jpg)
[flutter topic] 66 diagram basic constraints box (I) yyds dry goods inventory

微信小程序安全登录,必须先校验微信返回openid,确保信息唯一性。

Tortoise 没有显示绿色图标

Want to be an equipment manager? If you meet these three conditions, you can

allegro 设计中显示网络飞线或关闭网络飞线的方法
![[together with Shangshui Shuo series] day 6-strong liver academic paper! The most detailed explanation!](/img/70/595a94ba19d29a56a4f0bb5964a199.png)
[together with Shangshui Shuo series] day 6-strong liver academic paper! The most detailed explanation!
随机推荐
Matlab exercises - image drawing exercises
Solve the problem that the cursor flashes after clicking a point when measuring the distance in Allegro
FPGA (VIII) RTL code IV (basic circuit design 1)
Quick sort, query the k-largest number of the sequence
Tupu software intelligent energy integrated management and control platform
[Shangshui Shuo series] the simplest subtitle configuration
How to optimize databases and tables
Sequence traversal of binary tree ii[one of sequence traversal methods - > recursive traversal + level]
2022-2028 global long wave infrared camera and camera core industry research and trend analysis report
FarrowTech的无线传感器采用橙群微电子的NanoBeacon蓝牙信标技术
使用gdb添加断点的几种方式
Equal wealth
Stm32l4 Series MCU ADC accurately calculates input voltage through internal reference voltage
Vscode plug-in used now
set time format
想当设备管理师?满足这三个报考条件就可以
Redu.us took the initiative to transform, and the operation leader of China's charging pile emerged
Etcd教程 — 第六章 Etcd之核心API V3
Potential learning C language - pointer explanation (Advanced)
[Algèbre linéaire] 1.1 déterminant du deuxième et du troisième ordre