PostgreSQL UUID Data Type

This article describes the PostgreSQL UUID data type and how to use UUIDs as primary keys.

A UUID is a universally unique identifier consisting of 32 hexadecimal digits followed by a hyphen.

Not like SERIAL, identity columns, and sequences, UUIDs are globally unique, not unique within a database or a table. UUIDs are better suited in a clustered environment.

PostgreSQL supports the UUID data type to store UUID value.

Generate UUID value

To generate UUIDs in PostgreSQL, use the gen_random_uuid() function as follows:

SELECT gen_random_uuid();
           gen_random_uuid
--------------------------------------
 d1f7b7c1-c0b6-4707-aa17-5055b09b3ae8
(1 row)

The gen_random_uuid() function generates a v4 version of UUID, to generate other versions of UUID, use the uuid-ossp module and use its functions:

  • uuid_generate_v1()
  • uuid_generate_v1mc()
  • uuid_generate_v3()
  • uuid_generate_v4()
  • uuid_generate_v5()

For more information on UUID generation functions, check out the uuid-ossp module documentation.

Note: the gen_random_uuid() function is only available in PostgreSQL v13 and later. In previous versions, use the functions provided by the uuid-ossp module to generate UUIDs.

PostgreSQL UUID Examples

In this example, you will create a table named fruits whose primary key is the UUID data type.

Create the fruits table :

CREATE TABLE fruits (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  name VARCHAR NOT NULL
);

In the fruits table, the data type of the id column is UUID, and the default value is provided by the gen_random_uuid() function.

Insert some rows into the fruits table using the following statement:

INSERT INTO fruits (name)
VALUES
    ('Apple'),
    ('Peach'),
    ('Banana')
RETURNING *;
                  id                  |  name
--------------------------------------+--------
 980dd890-f7fe-4fff-999d-873516108b2e | Apple
 617c7809-cec6-44aa-9ce3-59a988e5bf35 | Peach
 98edf248-42a2-496d-9b4a-16472f6f0a00 | Banana
(3 rows)

As you can see, the id column is populated with UUID values ​​generated by the gen_random_uuid() function.

Conclusion

This article describes the PostgreSQL UUID data type and how to use UUIDs as primary keys.