MySQL varchar maximum length, text type footprint analysis

MySQL rows in the table is the maximum size of 65,534 (the actual row starting from the second storage byte) bytes. Each BLOB and TEXT columns which only 5-9 bytes.

Then the actual maximum length under to verify varchar type:
Test Environment: MySQL version 5.7.19

//首先要设置下 mysql 为严格执行模式,不然 varchar 超出最大长度为自动转为 text 类型
set sql_mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";
[SQL]
CREATE TABLE test(
    va VARCHAR(21845)
)DEFAULT CHARSET=utf8;
1118 - Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

21,845 characters seen here, just as the utf-8 65,535 bytes, but when varchar save one byte or two bytes long data prefix +. If the length is greater than 255 varchar column declaration, the prefix length is two bytes, the maximum length should be varchar:

65532=65535-1-2(字节)
utf-8 下为 21844=65532/3(字符)

See Example:

[SQL]
CREATE TABLE test(
    va VARCHAR(21844)
)DEFAULT CHARSET=utf8;
Query OK, 0 rows affected

Then look at the number of bytes occupied in the actual text type line:

[SQL]
CREATE TABLE test1(
    va VARCHAR(21841),
    tx text
)DEFAULT CHARSET=utf8;
1118 - Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs

As can be seen the error message, Governor has exceeded the maximum length. See above,

Each BLOB and TEXT columns which only 5-9 bytes.

But va field has vacated the field to tx 9 bytes of space ah, why is not it.
Seen from the official documents

BLOB and TEXT types require 2, 3 or 4 bytes to record the length of column values, depending on the maximum possible length of this type.

So is the need for at least 10 bytes (9 + 1) space, and try again:

[SQL]
CREATE TABLE test1(
    va VARCHAR(21840),
    tx text
)DEFAULT CHARSET=utf8;
Query OK, 0 rows affected

See here, when the field vacated va 12 bytes of space, tables can be created.

varchar longest is 64k, but pay attention to here is the length of the entire row of 64k , taking into account the other column, if there is not null when there will be an occupation, for different character sets, the effective length is not the same, For example, utf8, up to 21,845, but also to remove the other column, but in general varchar store are good enough.

If you have a large text, consider using text, maximum energy to 4G. Efficiency is basically a char> varchar> text, but if you are using Innodb engine, it is recommended to use varchar instead of char. char and varchar can have default values, text does not specify a default value.

Guess you like

Origin www.cnblogs.com/Cecil_1995/p/10974415.html