This article describes how to correctly use strings in MySQL databases. it mainly describes the actual operation steps of MySQL database characters (strings). We all know the characters (strings) of MySQL database) in practice, it is often used, so you have better understanding of it and hope to bring you some help in this aspect.
Do not assume that the character type is CHAR in the MySQL database. The difference between CHAR and VARCHAR is that CHAR is of fixed length, as long as you define a field as CHAR (10 ), therefore, no matter whether the data you store reaches 10 bytes, it occupies 10 bytes of space, while VARCHAR is of a variable length, if the possible value of a field is not fixed, we only know that it cannot exceed 10 characters. it is the most cost-effective to define it as VARCHAR (10, the occupied space of the VARCHAR type is the actual length of its value plus 1.
Why + 1? This byte is used to save the actual length. From this + 1, we can also see that if a field has a maximum of 10 characters, and in most cases, it uses 10 characters, it is not feasible to use VARCHAR: in most cases, the actual occupied space is 11 bytes, occupying one more byte than CHAR (10.
For example, a table stores the stock name and code. The stock name is mostly in four words, that is, 8 bytes. the stock code is a six-digit number in Shanghai, shenzhen has four digits. These are fixed length, and the stock name must use CHAR (8). although the stock code is not fixed length, if VARCHAR (6) is used ), A stock code in Shenzhen actually occupies 5 bytes, while a stock code in Shanghai occupies 7 bytes! Considering that Shanghai has more shares than Shenzhen, VARCHAR (6) is not as good as CHAR (6.
Although the maximum length of a CHAR or VARCHAR can be up to 255, I think CHAR larger than 20 is almost useless.