viam0Zah
viam0Zah

Reputation: 26312

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?

Upvotes: 16

Views: 6367

Answers (3)

Bryan Agee
Bryan Agee

Reputation: 5052

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.

Upvotes: 13

Matthew Gilliard
Matthew Gilliard

Reputation: 9498

UUIDs are globally unique, and can be generated in parallel without communication between clustered DB servers. So "Object IDs are more synergistic with sharding and distribution.". UUIDs are typically stored in 128 bits.

Auto-incremented integers are more user-friendly (well, shorter and more memorable anyway), and automatically allow sorting by insertion-order. Integers are typically stored in 32 or 64 bits.

Upvotes: 9

Andrey
Andrey

Reputation: 60065

The main pro that you can generate them independently. Con is that it is larger.

Upvotes: 5

Related Questions