当前位置:网站首页>Why does MySQL index fail? When do I use indexes?
Why does MySQL index fail? When do I use indexes?
2022-07-06 21:14:00 【Recharge the brain】
Preface
MySql What is the most important thing to ensure the query speed , Of course it's an index , I had a clear understanding of this yesterday .
Here's the thing , Just two days ago, a configuration dual data source ,postgresql and mysql. postgre It's from other companies , Then the demand is when postgre When the database connection fails , Connect to local database , Then there was a problem with this yesterday ,MySQL Execution is unusually slow , alike sql,postgre use 200 millisecond ,mysql Straight to 10 second , I was shocked , Once upon a time mysql There was suspicion !!!∑(゚Д゚ノ)ノ, After a careful look, there was no index ヽ(ー_ー)ノ.
Because at first, it was easy , Directly copy the table creation statement of others , It hasn't changed ( This behavior must be taken as a warning ), After adding the index, it is dozens of times faster , transcend postgre, And then learn from the experience , Decide to review carefully , How can you make such a low-end mistake !
What is index
It's like the catalogue of a Book , With the catalog , You don't need to , Go page by page to find what bytes want to check , But quickly locate the data you want to query through the directory , It's that simple (*ω*)
Create index
Use CREATE INDEX Create index
CREATE INDEX Create an index for an existing table , But you can't create a primary key index with this
CREATE < Index name > ON < Table name > (< Name > [< length >] [ ASC | DESC])
< Index name >: Specify the index name . A table can create multiple indexes , But the name of each index in the table is unique .< Table name >: Specify the name of the table to create the index .< Name >: Specifies the name of the column to create the index . In general, you can consider the query statement in JOIN Clause and WHERE The columns that often appear in clauses are used as index columns .< length >: optional . Specifies to use the length Characters to create the index . Using a portion of a column to create an index helps reduce the size of the index file , Save space for index columns . In some cases , Only prefixes of columns can be indexed . There is a maximum limit on the length of an index column 255 Bytes (MyISAM and InnoDB The maximum upper limit of the table is 1000 Bytes ), If the length of the index column exceeds this limit , You can only index with the prefix of the column . in addition ,BLOB or TEXT Columns of type must also be indexed with prefixes .ASC|DESC: optional .ASCSpecifies that the index is arranged in ascending order ,DESCSpecifies that the indexes are arranged in descending order , The default isASC.
Use ALTER TABLE Create index
This and CREATE INDEX almost , But this can create all indexes ,CREATE INDEX Is to create an index ,ALTER TABLE Is to modify the table structure at the same time , To create an index , Let's have a taste .. There may be restrictions on creating indexes , But there must be no drop in modifying the structure
ALTER TABLE TABLE_NAME // Splice the following
ADD INDEX [< Index name >] [< Index type >] (< Name >,…) # Add a normal index
ADD PRIMARY KEY [< Index type >] (< Name >,…) # Add a primary key index
ADD UNIQUE [ INDEX | KEY] [< Index name >] [< Index type >] (< Name >,…) # Add a unique index
ADD FOREIGN KEY [< Index name >] (< Name >,…) # Add a foreign key index
Use CREATE TABLE Create index
When creating database tables , Just create the index , If the index is frequently modified later , Generally, it is design , Not well designed , You must consider carefully when designing
CONSTRAINT PRIMARY KEY [ Index type ] (< Name >,…) # Create the primary key of the new table at the same time
KEY | INDEX [< Index name >] [< Index type >] (< Name >,…) # Create the index of the new table at the same time
UNIQUE [ INDEX | KEY] [< Index name >] [< Index type >] (< Name >,…) # Create a unique index of the table while creating a new table
FOREIGN KEY < Index name > < Name > # When creating a new table, create the foreign key of the table
Type of index
MySQL There are not many types of indexes , Less commonly used , Like me working for several years , Most of them use ordinary indexes ( Except for the primary key ), Others are rarely used . I do not know! , What is the most commonly used index , Welcome to leave a message (^_−)*
primary key Primary
A table can only have one primary key index , No repetition 、 It is not allowed to be NULL;
General index Normal
This is a mysql The most basic index in , No restrictions , If it is CHAR,VARCHAR type ,length It can be less than the actual length of the field ; If it is BLOB and TEXT type , Must specify length.
unique index Unique
Similar to a normal index , But it will force the value of the column to be unique , Allow null value
Full-text index Full Text
It is generally used on columns that need full-text retrieval , Retrieving long text is the best , For short text, use General index better ,
Which columns are suitable for index creation
- Often Searched On the list of , It can greatly improve the search speed
- Often used in (JOIN) On connected columns ( This problem happened yesterday , The fields connected by multiple tables are not indexed , This causes the query to be extremely slow )
- Often (>,<,=,in Etc. range query ) Use index , Because the index will sort , The specified range is continuous , It can greatly improve the query speed .
- Often group by and order by Add an index to the field of , Improve grouping , The speed of sorting .
- This one is also well known , Is in the where Add an index to the following conditions , Of course, add , Indexing has overhead , Don't add .
Which columns are not suitable for indexing
- Query few columns , If you don't query according to this column , Indexing is highly recommended .
- There are many duplicate values , Or most columns without values , It is also recommended to add , If there are many repeated values , It does not significantly improve the query speed , It will increase the cost .
- For those defined as text, image and bit Columns of data type should not be indexed . The amount of data in these columns is either quite large , Or the value is very small .
Why are these columns not recommended to be indexed , If every column is indexed , The query will not be fast
Quick query , however increase 、 Delete 、 Change The efficiency of , Will be seriously affected , Because when adding, deleting and modifying , The index needs to be maintained , Apart from that , The index also takes up a certain amount of physical space
Index failure
- Index cannot store null value
- When querying, use is null Index cannot be used , Will scan the whole table
- When querying, use not exists Index cannot be used , Will scan the whole table
- When querying, use not in Index cannot be used , Will scan the whole table
summary :not I can't go to the index , It scans the whole tableWhy can't I use null Well ?
Because the index is ordered ,null Where the value is placed in the index is a problem , Of course there are solutions , You can write empty strings directly , Or substitute a specific value null value
- It is not suitable for columns with more duplicate data
This simple explanation , Now there is a user table , There are 10000 pieces of data , Then we add an index to the gender field , Gender only male or Woman , Then all the gender data in this table are women , When searching , The database will be queried in the index first , Then go to the table to query , Because they are all women , So I scanned the whole table .
If it's not indexed , Then I will only scan the whole table , Efficiency is definitely better than the above situation .
- Fuzzy query by prefix like '%XX' perhaps like '%XX%'
This is a little bit easier to understand , If the prefix is ambiguous , I definitely need to see one by one , Then we can find the right , This situation will cause full table scanning
- If MySQL It is expected that the whole table will be faster , No index will be used
- If there is... In the condition or , as long as or One of the conditions does not create an index , No index will be used ( Because the column without index is supposed to be scanned by the whole table ), If you want to use or, And want the index to work , Then add indexes to the conditions .
- The use of functions in index columns will also invalidate the index
- Index participation in calculation will also invalidate the index
- Type implicit conversion
Suppose the type we store in the database is varchar, But when we execute the query statement , direct writing select name from user where id=123, Pay attention to this id=123,123 Has not been '' wrap up , So it is int type , under these circumstances , It also invalidates the index
- Comparing two columns will also invalidate the index
For example, there is storage in the table Math scores and Chinese achievement , We need to check Math scores be better than Students with Chinese scores , In this case, the index will not take effect , Even if both fields have indexes .
- It's not equal to comparison != <>
It's possible not to go , But not all , Generally speaking, when the proportion of query result set is relatively small , Can walk the index , The index will not be used when the proportion is large . This is related to the proportion of the result set and the population . Use Unequal Be careful when operating .
- order by Cause index to fail , Sorting will scan the whole table
That's all for this article , There is still a part of the index knowledge points that is not mentioned , The next part continues
I am participating in the recruitment of nuggets technology community creator signing program , Click the link to sign up for submission .
边栏推荐
- Yyds dry inventory run kubeedge official example_ Counter demo counter
- js中,字符串和数组互转(一)——字符串转为数组的方法
- ICML 2022 | Flowformer: 任务通用的线性复杂度Transformer
- After working for 5 years, this experience is left when you reach P7. You have helped your friends get 10 offers
- 968 edit distance
- Hardware development notes (10): basic process of hardware development, making a USB to RS232 module (9): create ch340g/max232 package library sop-16 and associate principle primitive devices
- The biggest pain point of traffic management - the resource utilization rate cannot go up
- Three schemes of SVM to realize multi classification
- document. Usage of write () - write text - modify style and position control
- OSPF multi zone configuration
猜你喜欢

3D人脸重建:从基础知识到识别/重建方法!

The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop

Data Lake (VIII): Iceberg data storage format

Interviewer: what is the internal implementation of ordered collection in redis?

Reference frame generation based on deep learning
![[sliding window] group B of the 9th Landbridge cup provincial tournament: log statistics](/img/2d/9a7e88fb774984d061538e3ad4a96b.png)
[sliding window] group B of the 9th Landbridge cup provincial tournament: log statistics
![[redis design and implementation] part I: summary of redis data structure and objects](/img/2e/b147aa1e23757519a5d049c88113fe.png)
[redis design and implementation] part I: summary of redis data structure and objects

Infrared thermometer based on STM32 single chip microcomputer (with face detection)

硬件开发笔记(十): 硬件开发基本流程,制作一个USB转RS232的模块(九):创建CH340G/MAX232封装库sop-16并关联原理图元器件

ICML 2022 | Flowformer: 任务通用的线性复杂度Transformer
随机推荐
OneNote 深度评测:使用资源、插件、模版
el-table表格——sortable排序 & 出现小数、%时排序错乱
OSPF多区域配置
[MySQL] trigger
1500万员工轻松管理,云原生数据库GaussDB让HR办公更高效
Spiral square PTA
2022菲尔兹奖揭晓!首位韩裔许埈珥上榜,四位80后得奖,乌克兰女数学家成史上唯二获奖女性
document. Usage of write () - write text - modify style and position control
Why do job hopping take more than promotion?
请问sql group by 语句问题
Yyds dry inventory run kubeedge official example_ Counter demo counter
Forward maximum matching method
JS get array subscript through array content
3D face reconstruction: from basic knowledge to recognition / reconstruction methods!
document.write()的用法-写入文本——修改样式、位置控制
PG基础篇--逻辑结构管理(事务)
什么是RDB和AOF
This year, Jianzhi Tencent
JS operation DOM element (I) -- six ways to obtain DOM nodes
js中,字符串和数组互转(二)——数组转为字符串的方法