How to use UUID as a database primary key? (Java and Postgres examples)

Kanan Rahimov
2 min readAug 18, 2023
UUID as Primary Key (with examples)

Topics: why use UUID?

Exploring the benefits of UUIDs as primary keys in Java projects with PostgreSQL.


  • Universally unique across tables
  • It can be used as a unique reference
  • - One table with all types
  • - OR, type + UUID
  • Do not reveal any internal logic (order of records)
  • Safe. UUIDs do not reveal any information about the order of creation or the number of records in the database. Also, the chances of duplication are very low.

the annual risk of a given person being hit by a meteorite is estimated to be one chance in 17 billion, which means the probability is about 0.00000000006 (6 × 10−11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%.


  • Takes more storage space compared to an integer.
  • Performance. It can take longer to index, especially in larger data sets.