MySQL explain the calculation key_len

key_len index indicates the number of bytes used, this value can be determined according to the index to be used, particularly when the composite index, which determines how much of the index to be used is very important.
In calculating key_len, following are some points to consider:

  • Additional information index field: can be divided into fixed-length and variable-length data types discussed, when the index field is fixed length data types, such as char, int, datetime, the need is empty flag, the flag occupies 1 byte (for a field is not null, it is not required 1 byte); for variable-length data types, such as varchar, in addition to whether the tag is empty, also need to have length information, need to occupy two bytes.

  • For, char, varchar, blob, text character sets, etc., and also the length of the key len related characters, a character latin1 1 byte, a GBK character occupies 2 bytes, a UTF8 character takes three words section.

In summary, the following look at some examples:

Column Type KEY_LEN Remark
id int key_len = 4 + 1 int is 4bytes, allowed to be NULL, plus 1byte
id bigint not null key_len = 8 bigint is 8bytes
user char(30) utf8 key_len = 30 * 3 + 1 utf8 every character is 3bytes, allow is NULL, plus 1byte
user varchar(30) not null utf8 key_len = 30 * 3 + 2 utf8 3 bytes per character, type of variable-length data, plus 2bytes
user varchar(30) utf8 key_len = 30 * 3 + 2 + 1 utf8 3 bytes per character, allowing for the NULL, plus 1byte, variable-length data types, plus 2bytes
detail text(10) utf8 key_len = 30 * 3 + 2 + 1 TEXT intercepting part are dynamic column type.

Note: The key_len where only indicates when the filter condition for the selected index column, does not contain order by / group by this part of the selected index of the column.
For example, there is a joint index idx (c1, c2, c3) , 3 columns are are int not null, then the following SQL execution plan, the value of key_len 8 instead of 12:

select ... from tb where c1=? and c2=? order by c1;

Guess you like

Origin www.cnblogs.com/longqin/p/11646004.html