mysql varchar maximum length problem

A row of data in mysql can store up to 65535 bytes. If varchar(N) is used, the value of N depends on the character set used when creating the table. It takes 1, 2, and 3 bytes to store a character in latin1, gbk, and utf8 encoding, respectively. The experimental character set below is latin1.

If the data table has only one varchar field and the field is DEFAULT NULL, then the maximum length of the varchar field is 65532 bytes, that is, 65535-2-1=65532 bytes.

create table test3(a varchar(65533));

When there is only one field, max(N)=65535-2-1, 2 bytes are used to identify the actual occupied length (16bit), and 1 byte is used to identify the field NULL, so max(N)=65532.

When there are 9 fields, and they are all NULL by default, the max(N) of the last field i = 65535 - 2*9 - 1 - 8189*8 = 4.

create table test3(a varchar(8189) default null,b varchar(8189) default null,c varchar(8189),d varchar(8189),e varchar(8189),f varchar(8189),g varchar(8189),h varchar(8189),i varchar(5));

If the first 8 fields are NOT NULL by default, the max(N) of the last field i = 65535 - 2*9 - 8189*8 = 5

 create table test4(a varchar(8189) not null,b varchar(8189) not null ,c varchar(8189) not null,d varchar(8189) not null,e varchar(8189) not null,f varchar(8189) not null,g varchar(8189) not null,h varchar(8189) not null,i varchar(5));

If the first 8 fields are all NULL, the last field is not null, and the max(N) of the last field i = 65535 - 2*9 - 8189*8 = 5, which means that as long as any field is not null when the table is created , it will not occupy the NULL flag bit, saving 1 byte.

If the field type is mixed & the default is NULL, max(N) = 65535-4-2-1=65528

 create table test4(a varchar(65529),age int);

If one is not null, max(N) = 65535-4-2-1 = 65528

create table test4(a varchar(65529) not null,age int);

The above describes the maximum length of row data. The following describes the calculation of the length of the key when creating an index.

create table test0(a varchar(10),b varchar(10));
create index ab_idx on test0(a,b);
explain select a from test0;

key=(10+2+1)*2 = 26 bytes; 2 bytes are used to identify the actual occupied length (16bit), and 1 byte is used to identify the field NULL. If a field is modified to not null, then key=10*2 + 2*2+ 1 = 25, one less byte is because the field a is not null, saving one byte. The calculation of the key is still related to the character set, and latin1 is used here.

alter table test0 modify a varchar(10) not null;

refer to:

https://www.cnblogs.com/gomysql/p/3615897.html

https://dev.mysql.com/doc/refman/5.5/en/column-count-limit.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325527753&siteId=291194637