Store UUID v4 in MySQL

后端 未结 7 873
栀梦
栀梦 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:40

    The most space-efficient would be BINARY(16) or two BIGINT UNSIGNED.

    The former might give you headaches because manual queries do not (in a straightforward way) give you readable/copyable values. The latter might give you headaches because of having to map between one value and two columns.

    If this is a primary key, I would definitely not waste any space on it, as it becomes part of every secondary index as well. In other words, I would choose one of these types.

    For performance, the randomness of random UUIDs (i.e. UUID v4, which is randomized) will hurt severely. This applies when the UUID is your primary key or if you do a lot of range queries on it. Your insertions into the primary index will be all over the place rather than all at (or near) the end. Your data loses temporal locality, which was a helpful property in various cases.

    My main improvement would be to use something similar to a UUID v1, which uses a timestamp as part of its data, and ensure that the timestamp is in the highest bits. For example, the UUID might be composed something like this:

    Timestamp | Machine Identifier | Counter
    

    This way, we get a locality similar to auto-increment values.

提交回复
热议问题