当前位置:网站首页>Indexing best practices
Indexing best practices
2022-07-27 03:23:00 【tea-Sir】
Index best practices
establish demo surface
CREATE TABLE `employees` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(24) NOT NULL DEFAULT '' COMMENT ' full name ',
`age` int(11) NOT NULL DEFAULT '0' COMMENT ' Age ',
`position` varchar(20) NOT NULL DEFAULT '' COMMENT ' Position ',
`hire_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ' Entry time ',
PRIMARY KEY (`id`),
KEY `idx_name_age_position` (`name`,`age`,`position`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT=' Employee record form ';
INSERT INTO employees(name,age,position,hire_time) VALUES('LiLei',22,'manager',NOW());
INSERT INTO employees(name,age,position,hire_time) VALUES('HanMeimei',23,'dev',NOW());
INSERT INTO employees(name,age,position,hire_time) VALUES('Lucy',23,'dev',NOW());
1. Full match
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei';

EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22 AND position ='manager';

2. The leftmost prefix rule
If you index multiple columns , Follow the leftmost prefix rule . It means that the query starts from the left front of the index and does not skip the columns in the index , If you hit a non indexed column , Will go through the global index .
EXPLAIN SELECT * FROM employees WHERE name = 'Bill' and age = 31;

EXPLAIN SELECT * FROM employees WHERE age = 30 AND position = 'dev';
EXPLAIN SELECT * FROM employees WHERE position = 'manager';

3. Do nothing on the index column ( Calculation 、 function 、( Automatically or Manual ) Type conversion ), It will cause index invalidation and turn to full table scan
EXPLAIN SELECT * FROM employees WHERE name = 'LiLei';

EXPLAIN SELECT * FROM employees WHERE left(name,3) = 'LiLei';

to hire_time Add a normal index :
Normal index :
EXPLAIN select * from employees where hire_time ='2022-07-24 20:10:22';

There is an index invalidation after time type conversion :
EXPLAIN select * from employees where date(hire_time) ='2018-09-30';

Convert to date range query , Can walk the index :
EXPLAIN select * from employees where hire_time >='2018-09-30 00:00:00' and hire_time <='2018-09-30 23:59:59';

Restore original index state
ALTER TABLE `employees` DROP INDEX `idx_hire_time`;
4. The storage engine cannot use the column to the right of the range condition in the index
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22 AND position ='manager';

EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age > 22 AND position ='manager';

When age When using range query , Hit is range, instead of ref, It has been inferior by one level ;
from ken_len It can be seen that , After the range query, the length becomes 78, explain age Subsequent index misses .
5. Try to use overlay index ( Queries that only access the index ( Index columns contain query Columns )), Reduce select * sentence
EXPLAIN SELECT name,age FROM employees WHERE name= 'LiLei' AND age = 23 AND position='manager';

EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 23 AND position ='manager';

from Extra Analysis can be seen ,select * Will result in failure to hit the index column .
6.mysql In use is not equal to (!= perhaps <>),not in ,not exists Unable to use the index will result in a full table scan < Less than 、 > Greater than 、 <=、>= these ,mysql The internal optimizer will, based on the retrieval ratio 、 Multiple factors such as table size are used to evaluate whether index is used as a whole
EXPLAIN SELECT * FROM employees WHERE name != 'LiLei';

Negative index (!、not etc. ) I don't usually go through the index , The range query determines whether to go to the index according to the judgment of the optimizer .
7.is null,is not null In general, you cannot use indexes
EXPLAIN SELECT * FROM employees WHERE name is null

8.like Start with a wildcard (‘$abc…’)mysql Index failure will become a full table scan operation
EXPLAIN SELECT * FROM employees WHERE name like '%Lei'

EXPLAIN SELECT * FROM employees WHERE name like 'Lei%'

Similar query like in , With "%“ Generally, the index is not used at the beginning , With ”%" The end can be indexed .
With "teasir%" ending , amount to =“teasir”, Naturally, you can go to the index .
problem : solve like’% character string %' Indexing methods that are not used ?
a) Use overlay index , The query field must be an override index field .
b) If you can't use overlay index, you may need to use search engine
9. String index is invalid without single quotation marks
EXPLAIN SELECT * FROM employees WHERE name = '1000';

EXPLAIN SELECT * FROM employees WHERE name = 1000;

The analysis shows that , The index is invalid without single quotation marks .
10. To use less or or in, When you use it to query ,mysql Not necessarily index ,mysql The internal optimizer will, based on the retrieval ratio 、 Overall evaluation of multiple factors such as table size Estimate whether to use index , See scope query optimization for details
EXPLAIN SELECT * FROM employees WHERE name = 'LiLei' or name = 'HanMeimei';

Try to use other logic to reduce or perhaps in Use .
11. Range query optimization
Add a single index to age
ALTER TABLE `employees` ADD INDEX `idx_age` (`age`) USING BTREE ;
explain select * from employees where age >=1 and age <=2000;

The reason why I didn't go to the index :mysql The internal optimizer will, based on the retrieval ratio 、 Multiple factors such as table size are used to evaluate whether index is used as a whole . Take this example , May be Because the amount of data in a single query is too large, the optimizer finally chooses not to go to the index An optimization method : You can divide a large area into several small areas
explain select * from employees where age >=1 and age <=2;

If the range query does not go through the index , Analyze whether it is due to the amount of data , Optimizer optimization leads to .
Restore original index state
ALTER TABLE `employees` DROP INDEX `idx_age`;
Summarized below :
The range query will hit the current field index (a=3 and b>4; Will hit b), Similar queries will not hit the current field index (a=3 and b like ‘%kk’; It won't hit b).
边栏推荐
猜你喜欢

Graphic SQL, this is too vivid!

After two years of graduation, I switched to software testing and got 12k+, and my dream of not taking the postgraduate entrance examination with a monthly salary of more than 10000 was realized

Details of impala implementation plan

It's too strong. An annotation handles the data desensitization returned by the interface

Portraiture5全新升级版磨皮滤镜插件神器
![[learn FPGA programming from scratch -54]: high level chapter - FPGA development based on IP core - principle and configuration of PLL PLL IP core (Altera)](/img/4f/f75cfeb4422120ef9ac70cdeb0a840.png)
[learn FPGA programming from scratch -54]: high level chapter - FPGA development based on IP core - principle and configuration of PLL PLL IP core (Altera)

阶乘末尾0的数量

An error in the fourth edition of the red book?

Message rejected MQ

Jmeter分布式压测
随机推荐
Social wechat applet of fanzhihu forum community
The diagram of user login verification process is well written!
Fastboot刷机
JMeter distributed pressure measurement
[flask] the server obtains the request header information of the client
185. All employees with the top three highest wages in the Department (mandatory)
Plato farm has a new way of playing, and the arbitrage eplato has secured super high returns
将幕布文章OPML转换为Markdown的方法
[understanding of opportunity -52]: the depth of communication varies from person to person
Jmeter分布式压测
How to visit the latest version of burpsuite pro in vain
正方形数组的数目(DAY 81)
架构基本概念和架构本质
最大连续子序列(DAY 77)
DNS记录类型及相关名词解释
[learning notes, dog learning C] string + memory function
Win10/win11 lossless expansion of C disk space, cross disk consolidation of C and e disks
Worthington过氧化物酶活性的6种测定方法
Docker creates MySQL 8.x container and supports Mac and arm architecture chips
子模块cache缓存失效