MySQL’s explain
statement is commonly used to analyze the cause of slow SQL and returns the following columns:
select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, extra.
The most important fields are type, rows, key and extra.
Logical Architecture of MySQL
Let’s start with the basics, the logical architecture of MySQL.
Client -> (Query Cache, 5.7.20 deprecated, 8.0 removed) -> Parser (generates parse trees) -> Preprocessor (generates new parse trees) -> Query Optimizer (generates query plans) -> Execution Engine (execution scheduling) -> Storage Engine (data lookup) -> Execution Engine (data filtering, sorting, etc.) -> Client and Query Cache
“type”, “rows” and “key” fields
The “type” field is used to indicate the type of connection. Connection types can be classified from fast to slow as follows:
const, system: up to one matching row, using a primary key or unique index
eq_ref: returns a row of data, usually found in
join
, using a primary key or a unique indexref: uses the leftmost prefix of the key, and the key is not a primary or unique key
range: index range scan, the scan of the index starts at a certain point and returns the matching row(s)
index: full table scan in the order of the index, the advantage is that there is no sorting, the disadvantage is that the whole table has to be scanned
all: full table scan