Why do I use UUID as a database primary key? (Java and Postgres examples)
Exploring the benefits of UUIDs as primary keys in Java projects with PostgreSQL.
Topics: why use UUID?
Advantages
- 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%.
Disadvantages
- Takes more storage space compared to an integer.
- Performance. It can take longer to index, especially in larger data sets.
- Index fragmentation. Due to their random nature, when UUIDs are used as a primary key, it can lead to index fragmentation. This fragmentation can negatively affect database performance over time by increasing disk I/O and query execution times.
Sequential vs. Random Order: Integer-based primary keys are typically generated in sequential order (e.g., 1, 2, 3, ...), which results in the physical storage of data in a relatively orderly manner. New records are often added at the end, maintaining the order of data on disk. This minimizes the need to rearrange or shift data blocks in storage.
Putting It Into Practice
Now, let's see how using UUIDs works in a real project.
I will use a Java Spring Boot project as an example.
Here is the Entity layer with UUID type:
@Entity
@Table(name = "item")
public class ItemEntity {
...
@Id
@UuidGenerator(style = UuidGenerator.Style.RANDOM)
private UUID id;
private String slug;
private String title;
private String description;
...
}
Here, `@UuidGenerator(style = UuidGenerator.Style.RANDOM)` will make sure to automatically generate UUID values and set it as ID.
SQL query to generate this table for the Postgres database would look like this:
CREATE TABLE item
(
id UUID NOT NULL,
created_at_utc TIMESTAMP WITHOUT TIME ZONE,
updated_at_utc TIMESTAMP WITHOUT TIME ZONE,
slug VARCHAR(255) NOT NULL UNIQUE,
title VARCHAR(255) NOT NULL,
description VARCHAR(255),
item_type VARCHAR(255),
item_group VARCHAR(255),
item_category VARCHAR(255),
inner_object TEXT,
CONSTRAINT pk_item PRIMARY KEY (id)
);
Watch this as a video tutorial and navigate using the transcribed text:
Or watch it on YouTube.
➕
Subscribe and Follow
* Subscribe to CoderVlogger.com and consider becoming a member.
* Check my Twitter for more up-to-date information.
* Subscribe to CoderVlogger.com and consider becoming a member.
* Check my Twitter for more up-to-date information.