postgresql
  1. postgresql-uuid

UUID - (PostgreSQL Data Types)

A universally unique identifier (UUID) is a type of identifier that is guaranteed to be unique across systems and time. PostgreSQL supports the UUID data type, which can be used to store UUIDs in a database table. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of UUID in PostgreSQL data types.

Syntax

The syntax for creating a uuid column in a PostgreSQL table is as follows:

CREATE TABLE table_name(
  column_name UUID PRIMARY KEY,
  ...
);

Example

CREATE TABLE employees (
  id UUID PRIMARY KEY,
  first_name VARCHAR(50) NOT NULL,
  last_name VARCHAR(50) NOT NULL,
  email VARCHAR(255) NOT NULL
);

INSERT INTO employees (id, first_name, last_name, email) VALUES (
  uuid_generate_v4(),
  'John',
  'Doe',
  'john.doe@example.com'
);

Output

SELECT * FROM employees;

 id                                    | first_name | last_name |        email
--------------------------------------+------------+-----------+---------------------
 bb2593f9-9bf4-4b79-af9d-3a75db3d6c45 | John       | Doe       | john.doe@example.com
(1 row)

Explanation

In this example, we created a table named employees with a uuid column named id. We used the uuid_generate_v4() function to generate a new UUID value for the id column when inserting data into the table.

The uuid_generate_v4() function is available in the uuid-ossp extension, which can be enabled with the following command:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

Use

The uuid data type can be used to store UUID values in a PostgreSQL table. This is useful when you need to generate unique identifiers for records in a table or when you want to store data that needs to be globally unique.

Important Points

  • The uuid data type can store UUID values with a length of 16 bytes.
  • The uuid-ossp extension must be enabled to use the uuid_generate_v4() function.
  • The uuid_generate_v4() function generates UUID values randomly.

Summary

In this tutorial, we discussed the uuid data type in PostgreSQL and its syntax, example, output, explanation, use, and important points. With this knowledge, you can now use the uuid data type to store UUID values in a PostgreSQL table.

Published on: