Store UUID v4 in MySQL

后端 未结 7 872
栀梦
栀梦 2020-12-08 06:58

I\'m generating UUIDs using PHP, per the function found here

Now I want to store that in a MySQL database. What is the best/most efficient MySQL field format for st

7条回答
  •  悲哀的现实
    2020-12-08 07:32

    If you always have a UUID for each row, you could store it as CHAR(36) and save 1 byte per row over VARCHAR(36).

    uuid CHAR(36) CHARACTER SET ascii
    

    In contrast to CHAR, VARCHAR values are stored as a 1-byte or 2-byte length prefix plus data. The length prefix indicates the number of bytes in the value. A column uses one length byte if values require no more than 255 bytes, two length bytes if values may require more than 255 bytes. https://dev.mysql.com/doc/refman/5.7/en/char.html

    Though be careful with CHAR, it will always consume the full length defined even if the field is left empty. Also, make sure to use ASCII for character set, as CHAR would otherwise plan for worst case scenario (i.e. 3 bytes per character in utf8, 4 in utf8mb4)

    [...] MySQL must reserve four bytes for each character in a CHAR CHARACTER SET utf8mb4 column because that is the maximum possible length. For example, MySQL must reserve 40 bytes for a CHAR(10) CHARACTER SET utf8mb4 column. https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html

提交回复
热议问题