Why should I choose UUID over an auto increment number for my entity's primary key? What are the pros and cons?
Pros. Using UUID for a primary key brings the following advantages: UUID values are unique across tables, databases, and even servers that allow you to merge rows from different databases or distribute databases across servers. UUID values do not expose the information about your data so they are safer to use in a URL.
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
The following are the advantages of using UUID for a primary key: UUID values in MySQL are unique across tables, databases, and servers. It allows us to merge rows from distributed/different databases across servers. UUID values do not provide information about our data, which means it is hard to guess.
Not possible. With the exception of the 6-bits reserved for the version and variant fields, v4 UUIDs consist of completely random data - i.e. there is no inherent notion of "sequence" within which to define meaningful increment / decrement operations.
Andrey and Mjg both had good points, but I would add a related performance issue that is significant.
With the decoupling of database and key generation also allows applications that have complex relationships between objects to create them all with the keys in place, so that bulk inserts are possible.
In the case of auto-increment, all of the objects that own relationships (ie the tables with foreign keys) have to wait for the other side of the relationship (ie the table the foreign key comes from) to save, query the assigned ids, and then individually update the records former records.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With