Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Postgres performance optimization and best practices guide maintained by Supabase
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/schema-primary-keys.md
1---2title: Select Optimal Primary Key Strategy3impact: HIGH4impactDescription: Better index locality, reduced fragmentation5tags: primary-key, identity, uuid, serial, schema6---78## Select Optimal Primary Key Strategy910Primary key choice affects insert performance, index size, and replication11efficiency.1213**Incorrect (problematic PK choices):**1415```sql16-- identity is the SQL-standard approach17create table users (18id serial primary key -- Works, but IDENTITY is recommended19);2021-- Random UUIDs (v4) cause index fragmentation22create table orders (23id uuid default gen_random_uuid() primary key -- UUIDv4 = random = scattered inserts24);25```2627**Correct (optimal PK strategies):**2829```sql30-- Use IDENTITY for sequential IDs (SQL-standard, best for most cases)31create table users (32id bigint generated always as identity primary key33);3435-- For distributed systems needing UUIDs, use UUIDv7 (time-ordered)36-- Requires pg_uuidv7 extension: create extension pg_uuidv7;37create table orders (38id uuid default uuid_generate_v7() primary key -- Time-ordered, no fragmentation39);4041-- Alternative: time-prefixed IDs for sortable, distributed IDs (no extension needed)42create table events (43id text default concat(44to_char(now() at time zone 'utc', 'YYYYMMDDHH24MISSMS'),45gen_random_uuid()::text46) primary key47);48```4950Guidelines:5152- Single database: `bigint identity` (sequential, 8 bytes, SQL-standard)53- Distributed/exposed IDs: UUIDv7 (requires pg_uuidv7) or ULID (time-ordered, no54fragmentation)55- `serial` works but `identity` is SQL-standard and preferred for new56applications57- Avoid random UUIDs (v4) as primary keys on large tables (causes index58fragmentation)5960Reference:61[Identity Columns](https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-GENERATED-IDENTITY)62