10.8.1 Optimizing Queries with EXPLAIN (original) (raw)
10.8.1 Optimizing Queries with EXPLAIN
The EXPLAIN statement provides information about how MySQL executes statements:
- EXPLAIN works withSELECT,DELETE,INSERT,REPLACE, andUPDATE statements.
- When EXPLAIN is used with an explainable statement, MySQL displays information from the optimizer about the statement execution plan. That is, MySQL explains how it would process the statement, including information about how tables are joined and in which order. For information about usingEXPLAIN to obtain execution plan information, see Section 10.8.2, “EXPLAIN Output Format”.
- When EXPLAIN is used with
FOR CONNECTION_`connectionid`_
rather than an explainable statement, it displays the execution plan for the statement executing in the named connection. See Section 10.8.4, “Obtaining Execution Plan Information for a Named Connection”. - For SELECT statements,EXPLAIN produces additional execution plan information that can be displayed usingSHOW WARNINGS. SeeSection 10.8.3, “Extended EXPLAIN Output Format”.
- EXPLAIN is useful for examining queries involving partitioned tables. SeeSection 26.3.5, “Obtaining Information About Partitions”.
- The
FORMAT
option can be used to select the output format.TRADITIONAL
presents the output in tabular format. This is the default if noFORMAT
option is present.JSON
format displays the information in JSON format.
With the help of EXPLAIN, you can see where you should add indexes to tables so that the statement executes faster by using indexes to find rows. You can also useEXPLAIN to check whether the optimizer joins the tables in an optimal order. To give a hint to the optimizer to use a join order corresponding to the order in which the tables are named in aSELECT statement, begin the statement with SELECT STRAIGHT_JOIN
rather than just SELECT. (SeeSection 15.2.13, “SELECT Statement”.) However,STRAIGHT_JOIN
may prevent indexes from being used because it disables semijoin transformations. SeeOptimizing IN and EXISTS Subquery Predicates with Semijoin Transformations.
The optimizer trace may sometimes provide information complementary to that of EXPLAIN. However, the optimizer trace format and content are subject to change between versions. For details, seeSection 10.15, “Tracing the Optimizer”.
If you have a problem with indexes not being used when you believe that they should be, run ANALYZE TABLE to update table statistics, such as cardinality of keys, that can affect the choices the optimizer makes. SeeSection 15.7.3.1, “ANALYZE TABLE Statement”.