PostgreSQL UUID Data Type
Summary: in this tutorial, you will learn about the PostgreSQL UUID data type and how to generate UUID values using a supplied module.
Introduction to PostgreSQL UUID type
UUID stands for Universal Unique Identifier defined by RFC 4122 and other related standards.
A UUID value is a 128-bit quantity generated by an algorithm that makes it unique in the known universe using the same algorithm.
The following shows some examples of UUID values:
A UUID is a sequence of 32 digits of hexadecimal digits represented in groups separated by hyphens.
Because of its uniqueness feature, you often find UUID in distributed systems because it guarantees a better uniqueness than the SERIAL
data type which generates unique values within a single database.
To store UUID values in the PostgreSQL database, you use the UUID data type.
Generating UUID values
PostgreSQL provides you with a function to generate a UUID:
The gen_random_uuid()
function returns a version 4 (random) UUID. For example:
Output:
Creating a table with a UUID column
We will create a table whose primary key is a UUID data type. Additionally, the values of the primary key column will be generated automatically using the gen_random_uuid()
function.
First, create the contacts
table:
In this statement, the data type of the contact_id
column is UUID
.
The contact_id
column has a default value provided by the gen_random_uuid()
function, therefore, whenever you insert a new row without specifying the value for the contact_id column
, PostgreSQL will call the gen_random_uuid()
function to generate the value for it.
Second, insert some data into the contacts
table:
Output:
The output indicates that the contact_id
column has been populated by the UUID values generated by the gen_random_uuid()
function.
Using uuid-ossp module in the old version of PostgreSQL
If you use an old version of PostgreSQL, you need to use a third-party module uuid-ossp that provides specific algorithms to generate UUIDs
To install the uuid-ossp
module, you use the CREATE EXTENSION
statement as follows:
The IF NOT EXISTS
clause allows you to avoid re-installing the module.
If you want to generate a UUID value, you can use the uuid_generate_v4()
function. For example:
Output:
For more information on the functions for UUID generation, check out the uuid-ossp module documentation.
Summary
- UUID stands for Universal Unique Identifier.
- Use the
gen_random_uuid()
function to generate a version 4 (random) UUID.