Mysql calculates the length of a string

Mysql calculates the length of a string

In MySQL, char_length(str) and length(str) are built-in functions for determining length, and the length of a string can be obtained based on them; char_length(str) calculation unit:
character
.
Whether it is a Chinese character, a number, or a letter, it is considered a character
length(str)
Calculation unit: byte
UTF8 encoding: three bytes for a Chinese character, one byte for a number or letter.
gbk encoding: one Chinese character with two bytes, one number or letter with one byte.

length()<>char_length() can be used to check whether it contains Chinese characters

Extension:
After MySQL version 5.0.3, the calculation method of varchar type size has changed, from the earliest byte-based size varchar(length) to varchar(char_length).

1) Before MySQL 5.0.3:

Data type size: 0--255 bytes
Detailed explanation: 20 in varchar(20) represents the number of bytes. If UTF-8 encoding is stored, only 6 Chinese characters can be stored. varchar(n), where n represents the number of bytes.
2) After MySQL 5.0.3:

Data type size: 0--65535 bytes, but occupies up to 65532 bytes (two bytes are needed to store the length, and 1 byte is used to store the length if it is less than 255 bytes) Detailed explanation: varchar(20) represents the number of characters
, No matter what encoding, whether it is English or Chinese, 20 can be stored.

Reference: https://blog.csdn.net/qq_39390545/article/details/106618423

Guess you like

Origin blog.csdn.net/sinat_30603081/article/details/132203207