Skip to main content
The uuid-ossp extension provides functions to generate universally unique identifiers (UUIDs) using one of several standard algorithms. It is useful for creating unique primary keys that are unique across distributed systems. For more information, see the official PostgreSQL uuid-ossp Documentation.

Quick Start

Step 1: Enable Extension

Enable the extension in your database:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

Step 2: Generate UUIDs

Generate a random Version 4 UUID (most common):
SELECT uuid_generate_v4();
Expected Output:
           uuid_generate_v4           
--------------------------------------
 a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11
Generate a Version 1 UUID (timestamp & MAC address):
SELECT uuid_generate_v1();

Step 3: Use as Primary Key

Create a table using UUID as the primary key with a default value:
CREATE TABLE users (
    user_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    username VARCHAR(50),
    email VARCHAR(100)
);

INSERT INTO users (username, email) VALUES
    ('john_doe', '[email protected]'),
    ('jane_smith', '[email protected]');

SELECT * FROM users;

Functions

FunctionReturn TypeDescription
uuid_generate_v1()uuidGenerates a version 1 UUID using MAC address and timestamp.
uuid_generate_v1mc()uuidGenerates a version 1 UUID using a random multicast MAC address.
uuid_generate_v3(namespace, name)uuidGenerates a deterministic version 3 UUID (MD5) from namespace and name.
uuid_generate_v4()uuidGenerates a random version 4 UUID.
uuid_generate_v5(namespace, name)uuidGenerates a deterministic version 5 UUID (SHA-1) from namespace and name. Preferred over v3.