Performance analysis of MySQL index

TandK 2021-01-21 18:16:35
performance analysis mysql index

Why do you do performance analysis

Do you have a situation like this .

In front of a person you haven't written much about 、 Complex business , You've been thinking about it for a long time , Finally, I started typing the first piece of code .

The process of writing is vague , Sometimes I can make myself dizzy .

But you finally finished it .

But click on a run , Finished , Yes bug.

What do I do ?

debug There are many ways , Console printing is a kind of .

Information printed through the console , We can modify the code based on the feedback , Until the code works .

It's the same with building an index .

Last post 《 Talking about sql Indexes 》, I said that the difficulty of index is to make the most appropriate index for a specific table .

Because it doesn't just depend on what's in your watch , It depends more on your business , What keywords do you often search for in your business .

We can write code every day , Index can't be built every day .

So most of the time , Because I'm not familiar , The indexes we build in the beginning are often not the best , Only adjust the index according to the feedback , In order to make a most suitable index for this table .

What I want to share today is how to understand this feedback , That is how to do performance analysis .

How to do performance analysis

Use EXPLAIN keyword !

Use EXPLAIN Keywords can tell MySQL How to deal with you SQL Of the statement , Analyze the performance bottleneck of your query statement or table structure .

but EXPLAIN It doesn't give us direct feedback on the quality of the index we built .

The usage is like this , We built the index , Take the most common sentences in business SQL Statement to EXPLAIN once , If the feedback works well , Then the index is the most suitable for this table , On the contrary, it needs to be improved .

Or change the index , If you don't change SQL.

EXPLAIN How to play


explain To view sql sentence ( Horizontal table ) or explain To view sql sentence \G( Vertical table )

A concrete example

Each field explains

As can be seen from the picture above ,explain The information that comes out has the following fields :

id select_type table type possible_keys key key_len ref rows Extra

Take a close look at , Is it a bit like a payslip ?

The meaning of each field is like this :

  • id: View the read order of the table .

     The example above only queries one table , But if it's a multi table joint query , Then there are :
    id Same words , The order of execution is from top to bottom ;
    id Different words ,id The higher the value, the higher the priority ;
  • select_type: Show differential union queries 、 Subquery 、 General query, etc .

     Here are the possible values , And the corresponding information :
    SIMPLE -- ordinary select Inquire about , Does not contain subqueries or union;
    PRIMARY -- If the query contains any complex sub parts , The outermost query is marked PRIMARY;
    SUBQUERY -- stay select or where Include subqueries ;
    DERIVED -- stay from The list contains subqueries marked as DERIVED( derivative ),MySQL These subqueries will be executed recursively , Put the results on the provisional list ;
    UNION -- If the second select Appear in the union after , Is marked as union; if union Included in from Clause , Outer layer select Will be marked as :DERIVED;
    UNION RESULT -- from union Table to get the result select;
  • table: Display table name .

  • type: Shows what type of query is used .

     Here are the possible values , And the corresponding information :
    system -- There is only one line in the table ( It's equal to the system table ), This is a const Special case of type , Not usually , Can ignore not remember .
    const -- Indicates that it is found through index once ,const For comparison primary key( Primary key ) perhaps unique( only ) Indexes . Because only one line of data is matched , So soon , If you put the primary key in where In the list ,mysql You can convert the query to a constant .
    eq_ref -- Unique scan index , For each index key , In the table ** It just happened to be ** There's a record that matches . Commonly used for primary key or unique index scanning .
    ref -- Non unique scan index , Returns all rows that match a single value . above `eq_ref` The multivalued case of . Such as where age=1,age=1 There's just one line of data , It shows eq_ref,age=1 There are multiple lines of data , It shows ref.
    range -- Retrieve only rows in the given range , Use an index to select rows . If type The value of the column is `range`,key Column will show which index is used . It's usually in where In the sentence between、<、>、in And so on . This kind of range scan query is better than full table scan .
    index -- Full Index Scan( Scan all indexes ),index And ALL The difference for index Type only traverses the index tree . Read the whole watch , however index Read from index ,all It's read from the hard disk , And index files are usually smaller than data files .
    all -- Full Table Scan( Scan the whole table ), Traverse the entire table to find the matching rows , The index is totally useless .
    From the best to the worst is :system>const>eq_ref>ref>range>index>ALL
    details :
    1. type yes ALL, When the data reaches more than one million, it must be optimized .
    2. Generally speaking , If you want to optimize the query to at least range Level , It's best to achieve ref.
  • possible_keys and key

    possible_key: Show the indexes that may be applied to this table , One or more . Indexes that could theoretically be used , But it doesn't have to be actually used by the query .
    key: Actual index used , If null, No index is used .
    There are four situations in these two columns :
    1. possible_key Valuable ,key Valuable : normal , Sometimes the former has multiple values, but only one of the latter is normal .
    2. possible_key Valuable ,key No value :** Index failed , There's a problem **.
    3. possible_key No value ,key Valuable : Conditions of the query ( Such as where) No index or no condition query is used , But the columns of the query (select Later fields ) Just in sequence 、 The quantity is consistent with the index .
    4. possible_key No value ,key No value : normal , You didn't build the index .
  • key_len: Represents the number of bytes used in the index .

     This column can be used to calculate 【 The length of the index used in the query 】, With the same query results , The smaller the value, the better .
    key_len The displayed value is the maximum possible length of the index field , Instead of the actual length , It is calculated by table definition , It's not a search in a table .
    Suppose you build a composite index (col1,col2), If 【 adopt col1 Conditions of the query 】 and 【 adopt col1 and col2 Conditions of the query 】 The result is the same , So the former is better , Because you only need to use one field ,key_len The value of will be smaller , As mentioned above, it is determined by the length of the table definition key_len Value .
  • ref: Show key The value of the index reference in the column .

     There are two possible values , And the corresponding information :
    Library name . Table name . Field name -- Indicates which field of which database, which table the index refers to ;
    const -- The value representing the index reference is a constant , It's usually where id=1 That's how it comes out ;
  • rows: According to table statistics and index selection , Roughly estimate the number of rows that need to be read to find the record to be found .

  • Extra: Very important additional information .

     Here are the possible values , And the corresponding information :
    Using filesort -- explain mysql Completely or partially not sorted according to the index you built , It needs to be optimized .MySQL A sort operation that cannot be done with an index is called “ File sorting ”;
    Using temporary-- Temporary tables are used to save intermediate results ,mysql Use temporary tables when sorting query results . It also needs to be optimized , Because the creation and deletion of the temporary table are cost-effective , Common in order by and group by;
    Using index -- It means corresponding select The override index is used in the operation , Avoid accessing the data rows of the table , Good efficiency . If it appears at the same time Using where, Indicates that the index is used to perform a query of the key value of the index , If not , Indicates that the index is used to read data rather than perform lookup actions ;
    Using where -- Used where Filter ;
    Using join buffer -- Connection caching is used , If this field always appears , You can increase this value appropriately in the configuration file ;
    Impossible where -- where The value of the clause is always false, Can't be used to get any tuples ;
    Select tables optimized away -- In the absence of group by In the case of clause , Index based optimization MIN/MAX Operation or for MyISAM Storage engine optimization count(*) operation , You don't have to wait until the execution phase to do the calculation , The query execution plan generation phase completes the optimization ;
    distinct -- Optimize distinct operation , Stop looking for the same value immediately after finding the first set of matching tuples .
    Be careful :
    1. Use group by When sorting , If it's useful to index , It's best to follow the order of the index , such as , There is a composite index (col1,col2), When sorting, if you skip col1, Use it directly col2 Sort , Will lead to Using filesort、Using temporary And other serious problems .
    2. Try to use overlay index ,select The following column names are exactly in the order of the index created 、 The number is the same . In this way, the index can be used to read data directly , Avoid reading data rows from the table .

Case study

Finally, a simple case , I'll put the topic first , Let's think again , Finally, put the answer .


The requirement is to write SQL Execution order of .


  1. First of all to see id Column ,id The higher the priority, the higher , Index from id by 4 I'm going to start looking at , In this line table by t2, The query is t2, So the first thing to look for is the last part select name,id from t2.

  2. id by 3 This line ,table yes t1, So what we're looking for is select id,name from t1 where other_column=''; At the end of the line Extra Column Using where It also proves this point .

  3. id by 2 This line ,table yes t3, So what we're looking for is select id from t3; in addition ,key The column is primary The primary key is used as index ,Extra Column Using Index Indicates that the overlay index is used ( That is to say, the reference is in select Back ).

  4. id by 1 This line ,table yes , According to 【id by 3 The query result of the line of 】 To query ( You can also see the corresponding id by 3 Of that line select_type As a Derived), So what we're looking for is select,(select id from t3)d2 from (select id,name from t1 where other_column = '') d1

  5. id by NULL This business ,table yes <union1,4>, According to 【id by 1 and 4 The query results of those two lines 】 To achieve union Inquire about .

answer name,id from t2 id,name from t1 where other_column='' id from t3,(3.result)d2 from (2.result) d1
5.(4.result) union (1.result)

Finally, it is suggested to combine the explanation of each field above , It's best to have your own thinking process .


What I'm talking about today is how to look at it explain Result .

It's like our console prints information to see how the code works , It's over , If there is bug, We have to do something about it .

And we're just talking about how to look at it today , next step , It's how to change .


  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云