PostgreSQL – How to Generate and Insert uuid

The gen_random_uuid() function is used to generate a random UUID (Universally Unique Identifier) in PostgreSQL database. UUIDs are 128-bit identifiers that are often used as unique keys in database tables or for generating random values.

Here’s how you can use gen_random_uuid() to generate a random UUID in PostgreSQL:

SELECT gen_random_uuid();

When you execute above SQL query, it will return a randomly generated UUID in its standard format, which looks like this

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

Each “x” in the above format represents a hexadecimal digit.

You can use the result of gen_random_uuid() in various ways within your SQL queries or when inserting data into a table to generate unique identifiers. For example, if you want to insert a row into a table with a UUID column, you can use it like this:

INSERT INTO my_table (id, name, description) VALUES (gen_random_uuid(), 'John', 'A random user');

This will insert a new row with a randomly generated UUID as the id column value.

gen_random_uuid() generates random UUIDs, and the probability of generating the same UUID twice is extremely low due to the randomness of the generated values. However, it is theoretically possible to generate duplicates since it relies on randomness. If you require strict uniqueness guarantees, you should consider using other methods, such as UUID version 4, which is designed to be generated using a combination of time and random values to reduce the likelihood of collisions.

Similar Posts