当前位置:网站首页>[issue 259] uncover how count is executed in MySQL?
[issue 259] uncover how count is executed in MySQL?
2022-06-29 02:45:00 【Java collection】
Click on the above “Java selected ”, choice “ Set to star ”
Don't ask people why , Ask yourself why !
below Have a pleasant surprise , A message will be back , Have a craigslist !
Make progress every day , It's the beginning of success ...
List of articles
1. Preface
I believe before that , Many people just remember , I didn't understand , Only know count(*)、count(1) Including all lines , When it comes to statistical results , Column values of... Are not ignored NULL,count( Name ) Only the column name is counted , When it comes to statistical results , Column values of NULL The record of .
Let's analyze it in principle .
2. Build table
Same as before , Use the same table , There are nearly 10W Data
CREATE TABLE demo_info(
id INT NOT NULL auto_increment,
key1 VARCHAR(100),
key2 INT,
key3 VARCHAR(100),
key_part1 VARCHAR(100),
key_part2 VARCHAR(100),
key_part3 VARCHAR(100),
common_field VARCHAR(100),
PRIMARY KEY (id),
KEY idx_key1 (key1),
UNIQUE KEY uk_key2 (key2),
KEY idx_key3 (key3),
KEY idx_key_part(key_part1, key_part2, key_part3)
)ENGINE = INNODB CHARSET=utf8mb4;3. count How to execute ?
We often see such examples :
When you need to count how much data there is in the table , You will often use the following statements
SELECT COUNT(*) FROM demo_info;Because the records in clustered index and nonclustered index correspond one-to-one , Instead of columns contained in clustered index records ( Index columns + Primary key id) Is less than the clustered index ( All columns ) Records of the , Therefore, the same number of non clustered index records occupy less storage space than clustered index records .
If we use a nonclustered index to execute the above query , That is, count the non clustered indexes uk_key2 How many records are there in total , It is much less than directly counting the number of records in the clustered index I/O cost . So the optimizer will decide to use nonclustered indexes uk_key2 Execute the above query .
Be careful : It has been verified here ,uk_key2 Lower cost than other indexes .
Analyze the execution plan

When executing the above query ,server The layer will maintain a name count The variable of , then :
server Layer to layer InnoDB First record .
InnoDB find uk_key2 The first secondary index record , And return it to server layer ( Be careful : Because only the number of records is counted at this time , So you don't need to go back to the table ).
because count The argument to the function is
*,MySQL Will*As a constant 0 Handle . because 0 Not at all NULL,server Stratification count Variable plus 1.server Layer to layer InnoDB To the next record .
InnoDB Recorded by secondary index next_record Property to find the next secondary index record , And return it to server layer .
server Continue to give count Variable plus 1.
Repeat the process , until InnoDB towards server The layer returns a message that has no record to check .
server The layer will eventually count The value of the variable is sent to the client .
4. count(1),count(id),count( Non indexed column ),count( Secondary index column ) Analysis of
Let's see count(1)
SELECT COUNT(1) FROM demo_info; Carry out the plan and count(*) equally

about count(*)、count(1) Or whatever count( constant ) Come on , It doesn't really matter which index record to read , because server The layer only cares about whether the storage engine reads the record , There is no need to extract the specified field from the record to judge whether it is NULL. So the optimizer will use the index that occupies the least storage space to execute the query .
Look again. count(id):
explain SELECT COUNT(id) FROM demo_info;
about count(id) Come on , because id It's the primary key , Whether it's clustered index records , Or will any secondary index record contain a primary key field , Therefore, in fact, reading records in any index can get id Field , At this time, the optimizer will also select the index that occupies the least storage space to execute the query .
Look again. count( Non indexed column )
explain select count(common_field) from demo_info
about count( Non indexed column ) Come on , The optimizer selects a full table scan , It indicates that only leaf nodes of the clustered index can be scanned sequentially .
Please make sure you understand the full table scan , It scans all leaf nodes of the clustered index in sequence and determines . in addition , More about mysql Interview questions , official account Java selected , reply java interview , Get the latest interview questions , Support online question brushing anytime, anywhere .
For other secondary index columns ,count( Secondary index column ), The optimizer can only select the index containing the column we specify to execute the query , Only non clustered indexes can be specified B+ Tree scan , The cost of index scanning that may lead to the optimizer's selection is not minimal .
in summary
about count(*)、count( constant )、count( Primary key ) Formal count In terms of functions , The optimizer can select the index with the lowest scanning cost to execute the query , So as to improve efficiency , Their execution process is the same , Just judging whether the expression is NULL Choose different ways to judge , The judgment is NULL The cost of the process is negligible , So we can say count(*)、count( constant )、count( Primary key ) The cost is the same .
And for count( Non indexed column ) Come on , The optimizer selects a full table scan , It indicates that only leaf nodes of the clustered index can be scanned sequentially .
count( Secondary index column ) You can only select the index containing the column we specify to execute the query , The cost of index execution that may cause the optimizer to select is not minimal .
In fact, these differences are due to the fact that non clustered index records occupy less storage space than clustered index records , Less and more I/O cost , So the optimizer has the choice of different indexes , That's it .
Copyright notice : This paper is about CSDN Blogger 「 Brick industry __」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
https://liuchenyang0515.blog.csdn.net/article/details/120851980
official account “Java selected ” The published content indicates the source of , All rights reserved ( Those whose copyright cannot be verified or whose source is not indicated all come from the Internet , Reprinted , The purpose of reprinting is to convey more information , The copyright belongs to the original author . If there is any infringement , Please contact the , The author will delete the first time !
------ THE END ------
Excellent materials , Great benefits !
>Java Interview questions <
3000+ Online brushing of test questions on the pavement , newest 、 The most complete Java Interview questions !


Hope to select Click on the title to jump to
【252 period 】 Praise , Yes volatile Key words explain the best article !
【254 period 】 these SQL The sentence really makes me stare !
【256 period 】MySQL in varchar Maximum length ?char and varchar What's the difference? ?
【257 period 】Java8 Of Stream It's not easy to debug ? try IDEA StreamTrace!
【258 period 】 How to use user-defined annotations Spring Security Project interface ?
technology Communication group !
Many people have asked recently , Is there any readers Communication group ! Want to know how to join ? It's very simple , Friends with similar interests , Just click on the card below , reply “ Add group ”, that will do No routine Join the communication group !
If the article helps , Looking at , Forward! !
边栏推荐
- Set set
- Quelques tests pour compléter l'environnement wasm
- table通过伪类实现 另类自适应
- String segment combination
- [linear algebra] 1.2 total permutation and commutation
- Table implements alternative adaptation through pseudo classes
- 字符串分段组合
- 温度转换 II
- String attribute exercise
- Informatics Olympiad all in one 1361: production | Luogu P1037 [noip2002 popularization group] production
猜你喜欢

18. `bs对象.节点名.next_sibling` 获取兄弟节点

What is a thread pool?

PWN beginner level0

Wechat applet custom component

Pvcreate ASM disk causes abnormal recovery of ASM disk group - sparing separation

Quelques tests pour compléter l'environnement wasm

PWN攻防世界guess_num

18. `bs object Node name next_ Sibling` get sibling nodes

18. `bs對象.節點名.next_sibling` 獲取兄弟節點

Oracle recovery tools actual batch bad block repair
随机推荐
哪个证券公司最大最安全 哪家券商服务好
PHP database ODBC
leetcode 统计无向图中无法互相到达点对数
How does sound amplify weak sounds
微信小程序自定义组件
[sans titre]
【一起上水硕系列】最简单的字幕配置
Leetcode counts the logarithm of points that cannot reach each other in an undirected graph
PHP SimpleXML
Kubernetes: container resource requirements and constraints (constraints)
Only in the past four years, Microsoft finally gave it up!
Calculate rectangular area
PWN攻防世界guess_num
PHP XML expat parser
China's flexible employment has reached 200million
18. `bs object Node name next_ Sibling` get sibling nodes
allegro对走好的线取消走线的方法
音响是如何把微弱声音放大呢
Set set
After today, I look forward to the new year's eve of the year of the rabbit