Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UUID versus auto increment number for primary key

Why should I choose UUID over an auto increment number for my entity's primary key? What are the pros and cons?

like image 769
viam0Zah Avatar asked Mar 01 '11 19:03

viam0Zah


People also ask

Is UUID good for primary key?

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.

Can auto increment be a primary key?

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.

Can I use UUID as primary key MySQL?

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.

Are UUIDs incremental?

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.


1 Answers

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.

like image 120
Bryan Agee Avatar answered Sep 19 '22 13:09

Bryan Agee