当前位置:网站首页>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 .ASC
Specifies that the index is arranged in ascending order ,DESC
Specifies 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 .
边栏推荐
- Study notes of grain Mall - phase I: Project Introduction
- Pinduoduo lost the lawsuit, and the case of bargain price difference of 0.9% was sentenced; Wechat internal test, the same mobile phone number can register two account functions; 2022 fields Awards an
- MLP (multilayer perceptron neural network) is a multilayer fully connected neural network model.
- 【mysql】触发器
- Interviewer: what is the internal implementation of ordered collection in redis?
- Select data Column subset in table R [duplicate] - select subset of columns in data table R [duplicate]
- Yyds dry goods count re comb this of arrow function
- SAP UI5 框架的 manifest.json
- The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix
- 966 minimum path sum
猜你喜欢
新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
1500萬員工輕松管理,雲原生數據庫GaussDB讓HR辦公更高效
What is the problem with the SQL group by statement
面试官:Redis中有序集合的内部实现方式是什么?
LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
Deployment of external server area and dual machine hot standby of firewall Foundation
嵌入式开发的7大原罪
Why do job hopping take more than promotion?
SAP UI5 框架的 manifest.json
After working for 5 years, this experience is left when you reach P7. You have helped your friends get 10 offers
随机推荐
愛可可AI前沿推介(7.6)
Reviewer dis's whole research direction is not just reviewing my manuscript. What should I do?
JS操作dom元素(一)——获取DOM节点的六种方式
通过数字电视通过宽带网络取代互联网电视机顶盒应用
How to turn a multi digit number into a digital list
It's almost the new year, and my heart is lazy
3D face reconstruction: from basic knowledge to recognition / reconstruction methods!
[200 opencv routines] 220 Mosaic the image
967- letter combination of telephone number
JS according to the Chinese Alphabet (province) or according to the English alphabet - Za sort &az sort
Swagger UI tutorial API document artifact
Tips for web development: skillfully use ThreadLocal to avoid layer by layer value transmission
[sliding window] group B of the 9th Landbridge cup provincial tournament: log statistics
Comprehensive evaluation and recommendation of the most comprehensive knowledge base management tools in the whole network: flowus, baklib, jiandaoyun, ones wiki, pingcode, seed, mebox, Yifang cloud,
c#使用oracle存储过程获取结果集实例
【深度学习】PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
基于STM32单片机设计的红外测温仪(带人脸检测)
面试官:Redis中有序集合的内部实现方式是什么?
el-table表格——sortable排序 & 出现小数、%时排序错乱
Laravel笔记-自定义登录中新增登录5次失败锁账户功能(提高系统安全性)