PostgreSQL – How to generate and insert a random uuid

Postgres database provides a gen_random_uuid() function to generate a random uuid. This function can be used in a sql insert statement to insert a random uuid into the unique column.

gen_random_uuid() function is included in the pgcrypto extension. Run the below command to install pgcrypto extension

create extension "pgcrypto"; 

Once pgcrypto is installed, you can run the below query to generate a random uuid.

select gen_random_uuid();

gen_random_uuid function can be used in an insert statement as shown below:

insert into tablename values(gen_random_uuid(),val2,val3);
See also  PostgreSQL - IN Operator