Why some MySQL data type require some extra bytes?

后端 未结 1 1305
闹比i
闹比i 2021-01-21 06:52

\"enter

I was reading about the MySQL data type size. I saw VARCHAR takes extra 1/2 bytes,

相关标签:
1条回答
  • 2021-01-21 07:28

    When MySQL (or any database or computer language) stores a variable length string, there are basically two ways to store the value:

    • The length can be encoded followed by the characters in the string
    • The end of the string can be marked by a special character (typically '0')

    Databases (almost?) always use length encoding. So, when you store 'ABC' as a variable length string, in the database storage it looks like:

    3  A  B  C
    

    When you store 'A':

    1  A
    

    That way, MySQL knows when one string ends and the next begins. The different lengths for the different types are based on the maximum length of the string. So, 1 byte can hold values from 0 to 255. 2 bytes can hold values from 0 to 65,535 and so on.

    When you use a regular character expression, say char(3), then 'ABC' looks like:

    A   B   C
    

    This occupies three bytes/whatever (depending on the character coding). The length is known from the table metadata.

    With char(3), the string 'A' also occupies three slots:

    A        
    ---^space here
    --------^space here
    

    The extra two are occupied by spaces. For long strings, this is generally a big waste of space, which is why most strings are stored as varchar rather than char.

    0 讨论(0)
提交回复
热议问题