Generating a UUID in Postgres for Insert statement?

UUID stands for universally unique identifier. Unlike auto generated ID’s it is long and includes both numeric and alphanumeric characters.

TL;DR: gen_random_uuid();

Randomness of a UUID is not based on an authority, also there is a possibility to be duplicated, in practice, that provides a unique identifier to objects in database.

UUID in PostgreSQL

PostgreSQL is natively supporting UUID generation, without any workarounds and hacks.

gen_random_uuid(); function generates a unique uuid, which can be included in insert statements.

Here you can find an example about how it generates a UUID value:

postgres=# select gen_random_uuid();
           gen_random_uuid            
--------------------------------------
 5e9e4b4e-70fb-42cd-ae2e-04a374ab223d
(1 row)

Let’s run this method a few more times:

postgres=# select gen_random_uuid();
           gen_random_uuid            
--------------------------------------
 e74d03ec-c1d7-418d-9132-35d50c028907
(1 row)

postgres=# select gen_random_uuid();
           gen_random_uuid            
--------------------------------------
 ab6a1207-0623-4743-a528-8d5e5ff457f3
(1 row)

postgres=# select gen_random_uuid();
           gen_random_uuid            
--------------------------------------
 8aafe82d-a69e-4106-89cd-e6194c1185ae
(1 row)

You can find gen_random_uuid documentation on PostgreSQL documentation for generating a uuid in Postgres.


Keep in touch

If you find our articles helpful, please leave a comment below. Have a question? Please do not hesitate to leave a comment below. I would like to hear from you, and try my best to get in touch with you as soon as possible.

A new post everyday, subscribe now and don’t miss it!

Subscribe to our newsletter for cool news

Hi! I’m an IT Specialist

I want to hear from you! I am Working with enterprises for 10+ years to improve their infrastructure and efficiency.

Get in touch with me.

Leave a Reply

Discover more from Empower. Innovate. Transform.

Subscribe now to keep reading and get access to the full archive.

Continue reading