Home  >  Q&A  >  body text

mysql optimization - If a mysql table cannot ensure that the field column lengths are consistent, does it not need to use char?

In a data table, if the length of each data column is fixed, then the length of each data row will also be fixed. As long as there is a variable length data column in the data table, then The length of each data row is variable. If the length of the data row in a certain data table is variable, then, in order to save storage space, MySQL will convert the fixed-length data in this data table into Columns are converted to corresponding variable length types, char data columns with a length less than 4 characters will not be converted to varchar types

If a field in a table is varchar, does it still make sense to create a char field in this table?

PHP中文网PHP中文网2704 days ago663

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-05-24 11:35:08

    First, you need to understand the difference between char and varchar.
    1. The length of CHAR is fixed, but the length of VARCHAR2 can be changed. For example, to store the string "abc", for CHAR (10), it means that the characters you store will occupy 10 bytes (including 7 null characters). The same VARCHAR2 (10) only occupies a length of 3 bytes, and 10 is only the maximum value. When the characters you store are less than 10, they are stored according to the actual length.
    2. CHAR is slightly more efficient than VARCHAR2.
    3. Currently VARCHAR is a synonym for VARCHAR2. The industry-standard VARCHAR type can store empty strings, but Oracle does not do so, although it reserves the right to do so in the future. Oracle has developed a data type VARCHAR2. This type is not a standard VARCHAR. It changes the feature that the varchar column in the database can store empty strings to store NULL values. If you want backward compatibility, Oracle recommends using VARCHAR2 instead of VARCHAR.
    When should you use CHAR and when should you use varchar2?
    CHAR and VARCHAR2 are a contradictory unity, and the two are complementary.
    VARCHAR2 saves space than CHAR, but is slightly less efficient than CHAR. That is, in order to gain efficiency, a certain amount of space must be sacrificed. This is what we often call 'trading space for efficiency' in database design.
    Although VARCHAR2 saves space than CHAR, if a VARCHAR2 column is frequently modified, and the length of the modified data is different each time, this will cause a 'Row Migration' phenomenon, which will cause redundant I/O. This should be avoided in database design and adjustment. In this case, it would be better to use CHAR instead of VARCHAR2.
    This answer is quoted from Baidu’s answer https://zhidao.baidu.com/ques...
    I think the answer is very detailed

    reply
    0
  • Cancelreply