1.环境
OS: CentOS 6.5 x64
MySQL: 5.6 for Linux (x86_64)
本例中用到的表,可以参考MySQL 库 和 样例表 创建脚本
2.优化第一步
拿到一个慢SQL时,第一步就是看执行计划并权衡是否可以加索引,就是这么简单,不要被高深莫测的人给蒙住说什么有更好的方法,告诉各位同学:没有更好的方法,看执行计划和权衡加索引就是最好的方法。然后才是考虑各种别的优化方案。
3.SQL优化注意几点
1).注意函数调用的次数,避免每行都调用一次
2).避免全表扫描,尤其是大表
3).定期执行Analyze Table
4).熟悉各个引擎的调优技术、索引技术和配置参数。主要引擎是MyISAM、InnoDB、MEMORY。
5).如果一个SQL太复杂,就拆分成一块一块地优化
6).调内存
7).注意锁
4.执行计划 EXPLAIN
要使用执行计划,首先要读懂执行计划,然后通过改写SQL和索引技术来改进执行计划。
MySQL5.6.3之前只有 SELECT 可以生成执行计划,5.6.3及之后的版本SELECT DELETE INSERT REPLACE UPDATE都可以生成执行计划。
explain语法:
{EXPLAIN | DESCRIBE | DESC}看到了吧,查看执行计划不只explain命令,desc也可以,结果一样。tbl_name
[col_name
|wild
]{EXPLAIN | DESCRIBE | DESC} [explain_type
]explainable_stmt
explain_type
: { EXTENDED | PARTITIONS | FORMAT =format_name
}format_name
: { TRADITIONAL | JSON}explainable_stmt
: { SELECT statement | DELETE statement | INSERT statement | REPLACE statement | UPDATE statement}
mysql> desc select * from p_range where id=12;
+----+-------------+---------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | p_range | const | PRIMARY | PRIMARY | 4 | const | 1 | NULL |
+----+-------------+---------+-------+---------------+---------+---------+-------+------+-------+
1 row in set (0.00 sec)
mysql> desc extended select * from p_range where id=12;
+----+-------------+---------+-------+---------------+---------+---------+-------+------+----------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows |filtered | Extra |
+----+-------------+---------+-------+---------------+---------+---------+-------+------+----------+-------+
| 1 | SIMPLE | p_range | const | PRIMARY | PRIMARY | 4 | const | 1 | 100.00 | NULL |
+----+-------------+---------+-------+---------------+---------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.02 sec)
有一个warning,可以看看
mysql> show warnings;
+-------+------+------------------------------------------------------------------------------------------+
| Level | Code | Message |
+-------+------+------------------------------------------------------------------------------------------+
| Note | 1003 | /* select#1 */ select '12' AS `id`,'员工JONES' AS `name` from `test`.`p_range` where 1 |
+-------+------+------------------------------------------------------------------------------------------+
1 row in set (0.04 sec)
警告信息显示优化器优化后执行的SQL。再看一个复杂点的:
mysql> desc extended select * from emp where deptno in (select deptno from dept where deptno=20);
+----+-------------+-------+-------+---------------+---------+---------+-------+------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+----------+-------------+
| 1 | SIMPLE | dept | const | PRIMARY | PRIMARY | 1 | const | 1 | 100.00 | Using index |
| 1 | SIMPLE | emp | ALL | NULL | NULL | NULL | NULL | 14 | 100.00 | Using where |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+----------+-------------+
2 rows in set, 1 warning (0.00 sec)
mysql> show warnings;
+-------+------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Level | Code | Message |
+-------+------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Note | 1003 | /* select#1 */ select `test`.`emp`.`empno` AS `empno`,`test`.`emp`.`ename` AS `ename`,`test`.`emp`.`job` AS `job`,`test`.`emp`.`mgr` AS `mgr`,`test`.`emp`.`hiredate` AS `hiredate`,`test`.`emp`.`sal` AS `sal`,`test`.`emp`.`comm` AS `comm`,`test`.`emp`.`deptno` AS `deptno` from `test`.`dept` join `test`.`emp` where (`test`.`emp`.`deptno` = 20) |
+-------+------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
从警告里可以看出优化器最终将*替换成所有的列名,这不但增加了sql文本的长度占用更多内存,还会使返回的数据量增大,所以在select列表里一定要写明所选列的列名,尤其当表中列特别多时更应写出列名,只选要查看的列。
mysql> desc partitions select * from p_range where id=12;
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | p_range | p0 | const | PRIMARY | PRIMARY | 4 | const | 1 | NULL |
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+-------+
1 row in set (0.00 sec)
执行计划的解释可以参与这里:http://dev.mysql.com/doc/refman/5.6/en/explain-output.html
以下摘录一部分:
EXPLAIN Output Columns
This section describes the output columns produced by EXPLAIN
. Later sections provide additional information about the type
and Extra
columns.
Each output row from EXPLAIN
provides information about one table. Each row contains the values summarized in Table 8.1, “EXPLAIN Output Columns”, and described in more detail following the table. Column names are shown in the table's first column; the second column provides the equivalent property name shown in the output when FORMAT=JSON
is used.
Table 8.1 EXPLAIN Output Columns
Column | JSON Name | Meaning |
---|---|---|
id |
select_id |
The SELECT identifier |
select_type |
None | The SELECT type |
table |
table_name |
The table for the output row |
partitions |
partitions |
The matching partitions |
type |
access_type |
The join type |
possible_keys |
possible_keys |
The possible indexes to choose |
key |
key |
The index actually chosen |
key_len |
key_length |
The length of the chosen key |
ref |
ref |
The columns compared to the index |
rows |
rows |
Estimate of rows to be examined |
filtered |
filtered |
Percentage of rows filtered by table condition |
Extra |
None | Additional information |
Note
JSON properties which are NULL
are not displayed in JSON-formatted EXPLAIN
output.
-
The
SELECT
identifier. This is the sequential number of theSELECT
within the query. The value can beNULL
if the row refers to the union result of other rows. In this case, thetable
column shows a value like<union
to indicate that the row refers to the union of the rows withM
,N
>id
values ofM
andN
. -
The type of
SELECT
, which can be any of those shown in the following table. A JSON-formattedEXPLAIN
exposes theSELECT
type as a property of aquery_block
, unless it isSIMPLE
orPRIMARY
. The JSON names (where applicable) are also shown in the table.select_type
ValueJSON Name Meaning SIMPLE
None Simple SELECT
(not usingUNION
or subqueries)PRIMARY
None Outermost SELECT
UNION
None Second or later SELECT
statement in aUNION
DEPENDENT UNION
dependent
(true
)Second or later SELECT
statement in aUNION
, dependent on outer queryUNION RESULT
union_result
Result of a UNION
.SUBQUERY
None First SELECT
in subqueryDEPENDENT SUBQUERY
dependent
(true
)First SELECT
in subquery, dependent on outer queryDERIVED
None Derived table SELECT
(subquery inFROM
clause)MATERIALIZED
materialized_from_subquery
Materialized subquery UNCACHEABLE SUBQUERY
cacheable
(false
)A subquery for which the result cannot be cached and must be re-evaluated for each row of the outer query UNCACHEABLE UNION
cacheable
(false
)The second or later select in a UNION
that belongs to an uncacheable subquery (seeUNCACHEABLE SUBQUERY
)DEPENDENT
typically signifies the use of a correlated subquery. See Section 13.2.10.7, “Correlated Subqueries”.DEPENDENT SUBQUERY
evaluation differs fromUNCACHEABLE SUBQUERY
evaluation. ForDEPENDENT SUBQUERY
, the subquery is re-evaluated only once for each set of different values of the variables from its outer context. ForUNCACHEABLE
, the subquery is re-evaluated for each row of the outer context.
SUBQUERYCacheability of subqueries differs from caching of query results in the query cache (which is described in Section 8.10.3.1, “How the Query Cache Operates”). Subquery caching occurs during query execution, whereas the query cache is used to store results only after query execution finishes.
When you specify
FORMAT=JSON
withEXPLAIN
, the output has no single property directly equivalent toselect_type
; thequery_block
property corresponds to a givenSELECT
. Properties equivalent to most of theSELECT
subquery types just shown are available (an example beingmaterialized_from_subquery
forMATERIALIZED
), and are displayed when appropriate. There are no JSON equivalents forSIMPLE
orPRIMARY
. -
The name of the table to which the row of output refers. This can also be one of the following values:
<union
: The row refers to the union of the rows withM
,N
>id
values ofM
andN
.<derived
: The row refers to the derived table result for the row with anN
>id
value ofN
. A derived table may result, for example, from a subquery in theFROM
clause.<subquery
: The row refers to the result of a materialized subquery for the row with anN
>id
value ofN
. See Section 8.2.1.18.2, “Optimizing Subqueries with Subquery Materialization”.
-
partitions
(JSON name:partitions
)The partitions from which records would be matched by the query. This column is displayed only if the
PARTITIONS
keyword is used. The value isNULL
for nonpartitioned tables. See Section 19.3.5, “Obtaining Information About Partitions”. -
The join type. For descriptions of the different types, see
EXPLAIN
Join Types. -
possible_keys
(JSON name:possible_keys
)The
possible_keys
column indicates which indexes MySQL can choose from use to find the rows in this table. Note that this column is totally independent of the order of the tables as displayed in the output fromEXPLAIN
. That means that some of the keys inpossible_keys
might not be usable in practice with the generated table order.If this column is
NULL
(or undefined in JSON-formatted output), there are no relevant indexes. In this case, you may be able to improve the performance of your query by examining theWHERE
clause to check whether it refers to some column or columns that would be suitable for indexing. If so, create an appropriate index and check the query withEXPLAIN
again. See Section 13.1.7, “ALTER TABLE Syntax”.To see what indexes a table has, use
SHOW INDEX
.
FROMtbl_name
-
The
key
column indicates the key (index) that MySQL actually decided to use. If MySQL decides to use one of thepossible_keys
indexes to look up rows, that index is listed as the key value.It is possible that
key
will name an index that is not present in thepossible_keys
value. This can happen if none of thepossible_keys
indexes are suitable for looking up rows, but all the columns selected by the query are columns of some other index. That is, the named index covers the selected columns, so although it is not used to determine which rows to retrieve, an index scan is more efficient than a data row scan.For
InnoDB
, a secondary index might cover the selected columns even if the query also selects the primary key becauseInnoDB
stores the primary key value with each secondary index. Ifkey
isNULL
, MySQL found no index to use for executing the query more efficiently.To force MySQL to use or ignore an index listed in the
possible_keys
column, useFORCE INDEX
,USE INDEX
, orIGNORE INDEX
in your query. SeeSection 8.9.3, “Index Hints”.For
MyISAM
andNDB
tables, runningANALYZE
helps the optimizer choose better indexes. For
TABLENDB
tables, this also improves performance of distributed pushed-down joins. ForMyISAM
tables, myisamchk --analyze does the same asANALYZE
. See Section 7.6, “MyISAM Table Maintenance and Crash Recovery”.
TABLE -
key_len
(JSON name:key_length
)The
key_len
column indicates the length of the key that MySQL decided to use. The length isNULL
if thekey
column saysNULL
. Note that the value ofkey_len
enables you to determine how many parts of a multiple-part key MySQL actually uses. -
The
ref
column shows which columns or constants are compared to the index named in thekey
column to select rows from the table.If the value is
func
, the value used is the result of some function. To see which function, useEXPLAIN
followed by
EXTENDEDSHOW WARNINGS
. The function might actually be an operator such as an arithmetic operator. -
The
rows
column indicates the number of rows MySQL believes it must examine to execute the query.For
InnoDB
tables, this number is an estimate, and may not always be exact. -
filtered
(JSON name:filtered
)The
filtered
column indicates an estimated percentage of table rows that will be filtered by the table condition. That is,rows
shows the estimated number of rows examined androws
×filtered
/100
shows the number of rows that will be joined with previous tables. This column is displayed if you useEXPLAIN
.
EXTENDED -
This column contains additional information about how MySQL resolves the query. For descriptions of the different values, see
EXPLAIN
Extra Information.There is no single JSON property corresponding to the
Extra
column; however, values that can occur in this column are exposed as JSON properties, or as the text of themessage
property.
EXPLAIN Join Types
The type
column of EXPLAIN
output describes how tables are joined. In JSON-formatted output, these are found as values of the access_type
property. The following list describes the join types, ordered from the best type to the worst:
-
The table has only one row (= system table). This is a special case of the
const
join type. -
The table has at most one matching row, which is read at the start of the query. Because there is only one row, values from the column in this row can be regarded as constants by the rest of the optimizer.
const
tables are very fast because they are read only once.const
is used when you compare all parts of aPRIMARY
or
KEYUNIQUE
index to constant values. In the following queries,tbl_name
can be used as aconst
table:SELECT * FROM
tbl_name
WHEREprimary_key
=1;SELECT * FROMtbl_name
WHEREprimary_key_part1
=1 ANDprimary_key_part2
=2; -
One row is read from this table for each combination of rows from the previous tables. Other than the
system
andconst
types, this is the best possible join type. It is used when all parts of an index are used by the join and the index is aPRIMARY
or
KEYUNIQUE NOT NULL
index.eq_ref
can be used for indexed columns that are compared using the=
operator. The comparison value can be a constant or an expression that uses columns from tables that are read before this table. In the following examples, MySQL can use aneq_ref
join to processref_table
:SELECT * FROM
ref_table
,other_table
WHEREref_table
.key_column
=other_table
.column
;SELECT * FROMref_table
,other_table
WHEREref_table
.key_column_part1
=other_table
.column
ANDref_table
.key_column_part2
=1; -
All rows with matching index values are read from this table for each combination of rows from the previous tables.
ref
is used if the join uses only a leftmost prefix of the key or if the key is not aPRIMARY
or
KEYUNIQUE
index (in other words, if the join cannot select a single row based on the key value). If the key that is used matches only a few rows, this is a good join type.ref
can be used for indexed columns that are compared using the=
or<=>
operator. In the following examples, MySQL can use aref
join to processref_table
:SELECT * FROM
ref_table
WHEREkey_column
=expr
;SELECT * FROMref_table
,other_table
WHEREref_table
.key_column
=other_table
.column
;SELECT * FROMref_table
,other_table
WHEREref_table
.key_column_part1
=other_table
.column
ANDref_table
.key_column_part2
=1; -
The join is performed using a
FULLTEXT
index. -
This join type is like
ref
, but with the addition that MySQL does an extra search for rows that containNULL
values. This join type optimization is used most often in resolving subqueries. In the following examples, MySQL can use aref_or_null
join to processref_table
:SELECT * FROM
ref_table
WHEREkey_column
=expr
ORkey_column
IS NULL; -
This join type indicates that the Index Merge optimization is used. In this case, the
key
column in the output row contains a list of indexes used, andkey_len
contains a list of the longest key parts for the indexes used. For more information, see Section 8.2.1.4, “Index Merge Optimization”. -
This type replaces
eq_ref
for someIN
subqueries of the following form:value
IN (SELECTprimary_key
FROMsingle_table
WHEREsome_expr
)unique_subquery
is just an index lookup function that replaces the subquery completely for better efficiency. -
This join type is similar to
unique_subquery
. It replacesIN
subqueries, but it works for nonunique indexes in subqueries of the following form:value
IN (SELECTkey_column
FROMsingle_table
WHEREsome_expr
) -
Only rows that are in a given range are retrieved, using an index to select the rows. The
key
column in the output row indicates which index is used. Thekey_len
contains the longest key part that was used. Theref
column isNULL
for this type.range
can be used when a key column is compared to a constant using any of the=
,<>
,>
,>=
,<
,<=
,IS NULL
,<=>
,BETWEEN
, orIN()
operators:SELECT * FROM
tbl_name
WHEREkey_column
= 10;SELECT * FROMtbl_name
WHEREkey_column
BETWEEN 10 and 20;SELECT * FROMtbl_name
WHEREkey_column
IN (10,20,30);SELECT * FROMtbl_name
WHEREkey_part1
= 10 ANDkey_part2
IN (10,20,30); -
The
index
join type is the same asALL
, except that the index tree is scanned. This occurs two ways:If the index is a covering index for the queries and can be used to satisfy all data required from the table, only the index tree is scanned. In this case, the
Extra
column saysUsing index
. An index-only scan usually is faster thanALL
because the size of the index usually is smaller than the table data.A full table scan is performed using reads from the index to look up data rows in index order.
Uses
does not appear in the
indexExtra
column.
MySQL can use this join type when the query uses only columns that are part of a single index.
-
A full table scan is done for each combination of rows from the previous tables. This is normally not good if the table is the first table not marked
const
, and usually very bad in all other cases. Normally, you can avoidALL
by adding indexes that enable row retrieval from the table based on constant values or column values from earlier tables.
EXPLAIN Extra Information
The Extra
column of EXPLAIN
output contains additional information about how MySQL resolves the query. The following list explains the values that can appear in this column. Each item also indicates for JSON-formatted output which property displays the Extra
value. For some of these, there is a specific property. The others display as the text of the message
property.
If you want to make your queries as fast as possible, look out for Extra
column values of Using filesort
and Using temporary
, or, in JSON-formattedEXPLAIN
output, for using_filesort
and using_temporary_table
properties equal to true
.
-
Child of '
(JSON:table
' pushed join@1message
text)This table is referenced as the child of
table
in a join that can be pushed down to the NDB kernel. Applies only in MySQL Cluster, when pushed-down joins are enabled. See the description of thendb_join_pushdown
server system variable for more information and examples. -
const row not found
(JSON property:const_row_not_found
)For a query such as
SELECT ... FROM
, the table was empty.tbl_name
-
Deleting all rows
(JSON property:message
)For
DELETE
, some storage engines (such asMyISAM
) support a handler method that removes all table rows in a simple and fast way. ThisExtra
value is displayed if the engine uses this optimization. -
Distinct
(JSON property:distinct
)MySQL is looking for distinct values, so it stops searching for more rows for the current row combination after it has found the first matching row.
-
FirstMatch(
(JSON property:tbl_name
)first_match
)The semi-join FirstMatch join shortcutting strategy is used for
tbl_name
. -
Full scan on NULL key
(JSON property:message
)This occurs for subquery optimization as a fallback strategy when the optimizer cannot use an index-lookup access method.
-
Impossible HAVING
(JSON property:message
)The
HAVING
clause is always false and cannot select any rows. -
Impossible WHERE
(JSON property:message
)The
WHERE
clause is always false and cannot select any rows. -
Impossible WHERE noticed after reading const
(JSON property:
tablesmessage
)MySQL has read all
const
(andsystem
) tables and notice that theWHERE
clause is always false. -
LooseScan(
(JSON property:m
..n
)message
)The semi-join LooseScan strategy is used.
m
andn
are key part numbers. -
Materialize
,Scan
(JSON:message
text)Before MySQL 5.6.7, this indicates use of a single materialized temporary table. If
Scan
is present, no temporary table index is used for table reads. Otherwise, an index lookup is used. See also theStart
entry.
materializeAs of MySQL 5.6.7, materialization is indicated by rows with a
select_type
value ofMATERIALIZED
and rows with atable
value of<subquery
.N
> -
No matching min/max row
(JSON property:message
)No row satisfies the condition for a query such as
SELECT
.
MIN(...) FROM ... WHEREcondition
-
no matching row in const table
(JSON property:message
)For a query with a join, there was an empty table or a table with no rows satisfying a unique index condition.
-
No matching rows after partition pruning
(JSON property:message
)For
DELETE
orUPDATE
, the optimizer found nothing to delete or update after partition pruning. It is similar in meaning toImpossible
for
WHERESELECT
statements. -
No tables used
(JSON property:message
)The query has no
FROM
clause, or has aFROM DUAL
clause.For
INSERT
orREPLACE
statements,EXPLAIN
displays this value when there is noSELECT
part. For example, it appears forEXPLAIN INSERT
because that is equivalent to
INTO t VALUES(10)EXPLAIN INSERT INTO t SELECT 10 FROM DUAL
. -
Not exists
(JSON property:message
)MySQL was able to do a
LEFT JOIN
optimization on the query and does not examine more rows in this table for the previous row combination after it finds one row that matches theLEFT
criteria. Here is an example of the type of query that can be optimized this way:
JOINSELECT * FROM t1 LEFT JOIN t2 ON t1.id=t2.id
WHERE t2.id IS NULL;Assume that
t2.id
is defined asNOT NULL
. In this case, MySQL scanst1
and looks up the rows int2
using the values oft1.id
. If MySQL finds a matching row int2
, it knows thatt2.id
can never beNULL
, and does not scan through the rest of the rows int2
that have the sameid
value. In other words, for each row int1
, MySQL needs to do only a single lookup int2
, regardless of how many rows actually match int2
. -
Range checked for each record (index map:
(JSON property:N
)message
)MySQL found no good index to use, but found that some of indexes might be used after column values from preceding tables are known. For each row combination in the preceding tables, MySQL checks whether it is possible to use a
range
orindex_merge
access method to retrieve rows. This is not very fast, but is faster than performing a join with no index at all. The applicability criteria are as described in Section 8.2.1.3, “Range Optimization”, andSection 8.2.1.4, “Index Merge Optimization”, with the exception that all column values for the preceding table are known and considered to be constants.Indexes are numbered beginning with 1, in the same order as shown by
SHOW
for the table. The index map value
INDEXN
is a bitmask value that indicates which indexes are candidates. For example, a value of0x19
(binary 11001) means that indexes 1, 4, and 5 will be considered. -
Scanned
(JSON property:N
databasesmessage
)This indicates how many directory scans the server performs when processing a query for
INFORMATION_SCHEMA
tables, as described in Section 8.2.4, “Optimizing INFORMATION_SCHEMA Queries”. The value ofN
can be 0, 1, orall
. -
Select tables optimized away
(JSON property:message
)The optimizer determined 1) that at most one row should be returned, and 2) that to produce this row, a deterministic set of rows must be read. When the rows to be read can be read during the optimization phase (for example, by reading index rows), there is no need to read any tables during query execution.
The first condition is fulfilled when the query is implicitly grouped (contains an aggregate function but no
GROUP
clause). The second condition is fulfilled when one row lookup is performed per index used. The number of indexes read determines the number of rows to read.
BYConsider the following implicitly grouped query:
SELECT MIN(c1), MIN(c2) FROM t1;
Suppose that
MIN(c1)
can be retrieved by reading one index row andMIN(c2)
can be retrieved by reading one row from a different index. That is, for each columnc1
andc2
, there exists an index where the column is the first column of the index. In this case, one row is returned, produced by reading two deterministic rows.This
Extra
value does not occur if the rows to read are not deterministic. Consider this query:SELECT MIN(c2) FROM t1 WHERE c1 <= 10;
Suppose that
(c1, c2)
is a covering index. Using this index, all rows withc1 <= 10
must be scanned to find the minimumc2
value. By contrast, consider this query:SELECT MIN(c2) FROM t1 WHERE c1 = 10;
In this case, the first index row with
c1 =
contains the minimum
10c2
value. Only one row must be read to produce the returned row.For storage engines that maintain an exact row count per table (such as
MyISAM
, but notInnoDB
), thisExtra
value can occur forCOUNT(*)
queries for which theWHERE
clause is missing or always true and there is noGROUP BY
clause. (This is an instance of an implicitly grouped query where the storage engine influences whether a deterministic number of rows can be read.) -
Skip_open_table
,Open_frm_only
,Open_trigger_only
,Open_full_table
(JSON property:message
)These values indicate file-opening optimizations that apply to queries for
INFORMATION_SCHEMA
tables, as described in Section 8.2.4, “Optimizing INFORMATION_SCHEMA Queries”.Skip_open_table
: Table files do not need to be opened. The information has already become available within the query by scanning the database directory.Open_frm_only
: Only the table's.frm
file need be opened.Open_trigger_only
: Only the table's.TRG
file need be opened.Open_full_table
: The unoptimized information lookup. The.frm
,.MYD
, and.MYI
files must be opened.
-
Start materialize
,End materialize
,Scan
(JSON:message
text)Before MySQL 5.6.7, this indicates use of multiple materialized temporary tables. If
Scan
is present, no temporary table index is used for table reads. Otherwise, an index lookup is used. See also theMaterialize
entry.As of MySQL 5.6.7, materialization is indicated by rows with a
select_type
value ofMATERIALIZED
and rows with atable
value of<subquery
.N
> -
Start temporary
,End temporary
(JSON property:message
)This indicates temporary table use for the semi-join Duplicate Weedout strategy.
-
unique row not found
(JSON property:message
)For a query such as
SELECT ... FROM
, no rows satisfy the condition for atbl_name
UNIQUE
index orPRIMARY KEY
on the table. -
Using filesort
(JSON property:using_filesort
)MySQL must do an extra pass to find out how to retrieve the rows in sorted order. The sort is done by going through all rows according to the join type and storing the sort key and pointer to the row for all rows that match the
WHERE
clause. The keys then are sorted and the rows are retrieved in sorted order. SeeSection 8.2.1.15, “ORDER BY Optimization”. -
Using index
(JSON property:using_index
)The column information is retrieved from the table using only information in the index tree without having to do an additional seek to read the actual row. This strategy can be used when the query uses only columns that are part of a single index.
For
InnoDB
tables that have a user-defined clustered index, that index can be used even whenUsing
is absent from the
indexExtra
column. This is the case iftype
isindex
andkey
isPRIMARY
. -
Using index condition
(JSON property:using_index_condition
)Tables are read by accessing index tuples and testing them first to determine whether to read full table rows. In this way, index information is used to defer (“push down”) reading full table rows unless it is necessary. See Section 8.2.1.6, “Index Condition Pushdown Optimization”.
-
Using index for group-by
(JSON property:using_index_for_group_by
)Similar to the
Using index
table access method,Using index for group-by
indicates that MySQL found an index that can be used to retrieve all columns of aGROUP
or
BYDISTINCT
query without any extra disk access to the actual table. Additionally, the index is used in the most efficient way so that for each group, only a few index entries are read. For details, see Section 8.2.1.16, “GROUP BY Optimization”. -
Using join buffer (Block Nested Loop)
,Using join buffer (Batched Key Access)
(JSON property:using_join_buffer
)Tables from earlier joins are read in portions into the join buffer, and then their rows are used from the buffer to perform the join with the current table.
(Block
indicates use of the Block Nested-Loop algorithm and
Nested Loop)(Batched Key Access)
indicates use of the Batched Key Access algorithm. That is, the keys from the table on the preceding line of theEXPLAIN
output will be buffered, and the matching rows will be fetched in batches from the table represented by the line in whichUsing
appears.
join bufferIn JSON-formatted output, the value of
using_join_buffer
is always either one ofBlock Nested Loop
orBatched Key Access
. -
Using MRR
(JSON property:message
)Tables are read using the Multi-Range Read optimization strategy. See Section 8.2.1.13, “Multi-Range Read Optimization”.
-
Using sort_union(...)
,Using union(...)
,Using intersect(...)
(JSON property:message
)These indicate how index scans are merged for the
index_merge
join type. See Section 8.2.1.4, “Index Merge Optimization”. -
Using temporary
(JSON property:using_temporary_table
)To resolve the query, MySQL needs to create a temporary table to hold the result. This typically happens if the query contains
GROUP
and
BYORDER BY
clauses that list columns differently. -
Using where
(JSON property:attached_condition
)A
WHERE
clause is used to restrict which rows to match against the next table or send to the client. Unless you specifically intend to fetch or examine all rows from the table, you may have something wrong in your query if theExtra
value is notUsing where
and the table join type isALL
orindex
.Using where
has no direct counterpart in JSON-formatted output; theattached_condition
property contains anyWHERE
condition used. -
Using where with pushed condition
(JSON property:message
)This item applies to
NDB
tables only. It means that MySQL Cluster is using the Condition Pushdown optimization to improve the efficiency of a direct comparison between a nonindexed column and a constant. In such cases, the condition is “pushed down” to the cluster's data nodes and is evaluated on all data nodes simultaneously. This eliminates the need to send nonmatching rows over the network, and can speed up such queries by a factor of 5 to 10 times over cases where Condition Pushdown could be but is not used. For more information, see Section 8.2.1.5, “Engine Condition Pushdown Optimization”.