Generate a Random UUID in YSQL

The UUID data type represents Universally Unique Identifiers (UUIDs).

A UUID is a sequence of 32 hexadecimal digits separated by hyphens (8 digits – 4 digits – 4 digits – 4 digits – 12 digits) representing the 128 bits.

Postgres 13 introduced a built-in core function named gen_random_uuid that returns a version 4 (random) UUID.

In versions of Postgres earlier than version 13, the gen_random_uuid function was avaialable only after installing the pgcrypto extension.

Currently, the YSQL API is based on Postgres 11.2, so we’ll need to install the pgcrypto extension to gain access to the gen_random_uuid function.

Example:

				
					yugabyte=# SELECT substring(version() from 'YB-([^\s]+)') "YB Version";
 YB Version
-------------
 2.17.0.0-b0
(1 row)

yugabyte=# SELECT gen_random_uuid();
ERROR:  function gen_random_uuid() does not exist
LINE 1: SELECT gen_random_uuid();
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

yugabyte=# CREATE EXTENSION pgcrypto;
CREATE EXTENSION

yugabyte=# SELECT gen_random_uuid();
           gen_random_uuid
--------------------------------------
 a27688dc-2ad0-44b5-8a3a-a1a8dbac5f5d
(1 row)
				
			

Have Fun!

Clearwater Beach - St. Pete, FL