In database design, when considering a primary key, what are the advantages and disadvantages of using UUID compared to a Long data type?
I came across two different tutorials that implemented each of them, and I am just curious about which one serves better.
Compare UUID and Long as the type of primary key in database:
1. Long:
Long or BigInt is 64-bit, less than UUID (128-bit).
Long is faster to generate, always generate unique ID, but not random. For example, in Spring Boot:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
This code will generate an increasing-from-0 key. For example:
0, 1, 2, ...
. Of course, an increasing-from-0 key won't be safe against something like XSS (because of its easy-to-predict property).
2. UUID:
558012d6-7db5-4053-b838-6a1ef4ad019b
), but it's random, a bit slower and much harder to predict. This means it's more secure than Long.In summary, both are good to use as the primary key in database. I think UUID is better, but I prefer to use Long because it's easier to implement in the program.