当前位置:网站首页>[MySQL string data type optimization] the difference between char and varchar

[MySQL string data type optimization] the difference between char and varchar

2022-06-09 18:15:00 InfoQ



Preface

Have studied MySQL Friends of the database must be right
char and varchar
These two string data types are not new , So these two types of
difference 、 Details and usage scenarios
Do you know ?


char And varchar contrast

  • char(size),
    Fixed length
    character string , Maximum 255 character .
  • varchar(size),
    Variable length
    character string , Maximum ==65535 byte ==( Notice that here are bytes , Characters occupy different bytes in different encoding rules ), If the table code is not defined
    The default is utf8
    【utf8 Maximum coding 21844 character ;gdk Code up to 32766 character 】
  • ( Pay attention to characters, not bytes )
  • char Assign fixed characters ,char(4) Occupy four characters , Save a character , It will also occupy four characters in memory .
  • varchar
    Allocate space according to actual use
    , Still need to use 1-3 Bytes to record the length of the stored content ,
    Total occupancy  = L( The actual data size )+(1-3) Bytes
    .

Code samples

CREATE TABLE t4(
 `name` CHAR(255));
# Create a table t4, Definition name The length of is 255 character
INSERT INTO t4 VALUES('ABCD');
INSERT INTO t4 VALUES(' I am you D');
# Add English... To the table 、 Chinese is OK
CREATE TABLE t5(
 `name` VARCHAR(32766)) CHARSET gbk;
# Define code as gdk, Maximum length is 32766 character , because gbk Chinese accounts for 2 Bytes , English 1 Bytes
CREATE TABLE t6(
 `name` VARCHAR(21844));
 # Define the code as the default utf8, Maximum length is 21844 character , because utf-8 Chinese accounts for 3 Bytes , English 1 Bytes

char And varchar Details of the use of

  • char(4), This 4 Indicates the number of characters , Non byte number , There are four letters in both Chinese and English ( The occupied character space is fixed ).
  • varchar(4), This 4 Also represents the number of characters , But the letters or Chinese characters stored here are
    Calculate according to the code when defining the table
    ( The occupied character space is not fixed ).

char and varchar The use of

  • Fixed data length , recommend char
    . for example md5 password ( Fix 32 by )、 Zip code 、 cell-phone number 、 ID number, etc .2.
      The length is uncertain , Use varchar
    . E.g. message 、 Articles, etc .
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091757457447.html