Skip to main content

How to Create UUID in PostgreSQL

Complete guide with gen_random_uuid() and uuid-ossp

PostgreSQL has had built-in UUID generation since version 13 — no extension required. Call gen_random_uuid() directly in a query or as a column default to get a random, RFC 4122-compliant identifier stored natively as 16 bytes instead of a 36-character string. Below you'll find copy-paste ready SQL for generating a PostgreSQL UUID, casting a string back into the UUID type, and the extension-based alternatives for versions before 13. Run the free uuid generator to create a cryptographically secure identifier for any application.

Generate UUID for PostgreSQL

SELECT gen_random_uuid();
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in PostgreSQL

The simplest way to generate a UUID in PostgreSQL (13 and later) is the built-in gen_random_uuid() function — no extensions, no setup. The rust uuid guide covers the uuid crate with feature flags for v4, v7, serde, and async runtime support.

psql
-- PostgreSQL 13+: gen_random_uuid() is built in, no extension needed
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) NOT NULL
);

-- Generate one directly in a query
SELECT gen_random_uuid();
-- Output: 550e8400-e29b-41d4-a716-446655440000

Explanation

Convert a String to a UUID in PostgreSQL

A UUID sent as a string — from an API request or an application layer — needs to be cast to PostgreSQL's native UUID type before it can be compared or stored efficiently. Try the uuid v4 generator for UUID v4 generation — the simplest, most private format for general-purpose identifiers.

psql
-- Cast a string literal to the UUID type
SELECT '550e8400-e29b-41d4-a716-446655440000'::uuid;

-- Or using CAST()
SELECT CAST('550e8400-e29b-41d4-a716-446655440000' AS uuid);

-- Comparing a string against a UUID column works via implicit cast
SELECT * FROM users WHERE id = '550e8400-e29b-41d4-a716-446655440000';

Explanation

Other Options for Generating UUIDs in PostgreSQL

PostgreSQL doesn't have native UUID v7 support yet, and versions before 13 need the uuid-ossp extension for any built-in generation function at all. The mongodb uuid reference explains UUID subtype 3 vs subtype 4 and their impact on query performance.

psql
-- PostgreSQL < 13: enable the uuid-ossp extension once per database
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Version 4 (random) via uuid-ossp
SELECT uuid_generate_v4();

-- Version 1 (timestamp + MAC address) via uuid-ossp
SELECT uuid_generate_v1();

-- UUID v7 (time-sortable) isn't built in yet -- generate it in application
-- code (see the python uuid / rust uuid guides) and insert it as a plain UUID.

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!