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-90865d1e13b1Method 2: uuid-ossp Extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
SELECT uuid_generate_v4();
-- a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11As 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-generatedUUID vs Serial
| UUID | Serial/BIGINT | |
|---|---|---|
| Size | 16 bytes | 4-8 bytes |
| Distributed safe | ✅ Yes | ❌ No |
| Index performance | Slower | Faster |
| Guessable | ❌ No | ✅ Yes |
Generate Online
Use our UUID Generator for quick UUIDs.