SQL

UUID Primary Keys

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
UUIDs as PKs avoid sequence contention across services and let clients generate IDs offline. v4 is random (worst for B-tree indexes); v7 is time-ordered (B-tree friendly).
SQL
Raw
-- PostgreSQL — uuid type + gen_random_uuid() (built-in since 13)
CREATE TABLE users (
    id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email       TEXT NOT NULL UNIQUE,
    created_at  TIMESTAMPTZ DEFAULT NOW()
);

INSERT INTO users (email) VALUES ('alice@x.com');
SELECT * FROM users;

-- Generate a UUID v4 on the fly
SELECT gen_random_uuid();

-- UUID v7 (time-ordered) — better for B-tree indexes, available via
-- the pg_uuidv7 extension or as a client-side generation in the app
-- (uuid library, ULID, etc.) Stripe uses prefixed IDs ("cus_...") for
-- the same reason — sortable + recognizable.

-- MySQL — UUID() returns the textual form
CREATE TABLE users (
    id    BINARY(16) PRIMARY KEY,         -- store binary for compactness
    email VARCHAR(255) NOT NULL UNIQUE
);
INSERT INTO users (id, email) VALUES (UUID_TO_BIN(UUID()), 'a@x.com');
SELECT BIN_TO_UUID(id), email FROM users;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.