How to Generate UUIDs in PostgreSQL

Published April 2025 · 3 min read

Method 1: Built-in (PostgreSQL 13+)

SELECT gen_random_uuid();
-- a81bc81b-dead-4e5d-abff-90865d1e13b1

Method 2: uuid-ossp Extension

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
SELECT uuid_generate_v4();
-- a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11

As Primary Key

CREATE TABLE users (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT UNIQUE
);

INSERT INTO users (name, email) VALUES ('John', 'john@example.com');
-- id is auto-generated

UUID vs Serial

UUIDSerial/BIGINT
Size16 bytes4-8 bytes
Distributed safe✅ Yes❌ No
Index performanceSlowerFaster
Guessable❌ No✅ Yes

Generate Online

Use our UUID Generator for quick UUIDs.

Related