According to MySQL website, the key_len
column indicates the length of the key that MySQL decided to use. The length is NULL
if the key column says NULL
. Note that the value of key_len enables you to determine how many parts of a multiple-part key MySQL actually uses.
Using an example from my previous question, I have an EXPLAIN SELECT statement that shows MySQL using an Index
with key_len: 6
. Below shows the composition of the index and columns used.
`Type` char(1) NOT NULL,
`tn` char(1) NOT NULL DEFAULT 'l',
`act` tinyint(1) unsigned NOT NULL DEFAULT '0',
`flA` mediumint(6) unsigned NOT NULL DEFAULT '0',
KEY `Index` (`Type`, `tn`, `act`, `flA`)
So how does the value of key_len
allows me to determine that my query uses the first three parts of a multiple-part key?
In the query, the columns have the same order as in the index. SQL uses statistics on the table's indexes to determine which index to use. The order of fields in the select statement has NO effect on which index to use. Statistics around indexes include information such as uniqueness of the index and other things.
To view a visual explain execution plan, execute your query from the SQL editor and then select Execution Plan within the query results tab. The execution plan defaults to Visual Explain , but it also includes a Tabular Explain view that is similar to what you see when executing EXPLAIN in the MySQL client.
Practically, indexes are also a type of tables, which keep primary key or index field and a pointer to each record into the actual table. The users cannot see the indexes, they are just used to speed up queries and will be used by the Database Search Engine to locate records very fast.
The key_len specifies the number of bytes that MySQL uses from the key.
Indexes are always used left_to_right. i.e. only the left-most part is used.
The length of your fields is as follows:
1 byte `Type` char(1) NOT NULL,
1 byte tn char(1) NOT NULL DEFAULT 'l',
1 byte act tinyint(1) unsigned NOT NULL DEFAULT '0',
3 bytes flA mediumint(6) unsigned NOT NULL DEFAULT '0',
1+1+1+3 = 6 bytes KEY `Index` (`Type`, `tn`, `act`, `flA`)
key usage always starts here ---^^^^^
If the key_len = 3 then it's using type+tn+act
.
Note that Key_len = 4 is impossible in this configuration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With