Detailed explanation of char and varchar in MySQL

(1) The difference between char and varchar in mysql

char: fixed length, high efficiency, generally used for form submission data storage of fixed length; for example: ID number, mobile phone number, phone number, password, etc.

varchar: variable length, low efficiency

 

(2) Detailed explanation

1. Changes in varchar type

(a) Storage Restrictions

The varchar field stores the actual content separately outside the clustered index. The actual length is represented by 1 to 2 bytes at the beginning of the content (2 bytes are required when the length exceeds 255), so the maximum length cannot exceed 65535.

(b) Code length limit

If the character type is gbk, each character occupies at most 2 bytes, and the maximum length cannot exceed 32766;

If the character type is utf8, each character occupies at most 3 bytes, and the maximum length cannot exceed 21845.

If the above limit is exceeded when defined, the varchar field will be forcibly converted to text type and a warning will be generated.

(c) Line length limit

What causes the varchar length limit in practical applications is a line-defined length. MySQL requires that the defined length of a row cannot exceed 65535. If the defined table length exceeds this value, prompt

ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. You have to change some columns to TEXT or BLOBs。

 

2. Differences between CHAR(M) and VARCHAR(M)

The biggest difference between CHAR and VARCHAR is that one is fixed length and the other is variable length. Since it is a variable length, the actual storage is the actual string plus a byte to record the length of the string (two bytes are required if it exceeds 255). If the value assigned to a CHAR or VARCHAR column exceeds the maximum length of the column, the value is clipped to fit. A warning is generated if the character being trimmed is not a space. Causes an error (instead of a warning) if non-whitespace characters are trimmed and disables insertion of values ​​by using strict SQL mode

 

 

 

 

 

 

 

 

 

.

Guess you like

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