HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMajor

PostgreSQL two different ways to generate a UUID: gen_random_uuid vs uuid_generate_v4?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlwaysuuid_generate_v4gen_random_uuiddifferenttwogenerateuuid

Problem

What is the difference between the following two functions

  • gen_random_uuid() provided by pgcrypto extension



  • uuid_generate_v4() provided by uuid-ossp extension



Are they both the same behind the scenes? Any performance impacts on using one?

Solution

Are they the same?

No.

The Postgres documetation for uuid-ossp suggests using gen_random_uuid() If you only need randomly-generated (version 4) UUIDs,

The uuid-ossp extension also provides other types of UUID (such as mac-addresses based)

The difference?

I looked at the source and discovered that

-
uuid_generate_v4() uses arc4random to determine the random part.

-
gen_random_uuid() uses fortuna instead.

Other than that they do the same job.

Notes:

  • gen_random_uuid() from the pgcrypto module is now deprecated, because it is natively part of PostgreSQL (since PostgreSQL version 13).



  • uuid_generate_v4() still requires the uuid-ossp module.

Context

StackExchange Database Administrators Q#205902, answer score: 32

Revisions (0)

No revisions yet.