Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Compare natural keys, auto-increment surrogate keys, and UUIDs for primary keys. Learn how UUIDv7 and sequential IDs impact B-tree index fragmentation.
Quick answer
Natural keys use existing domain attributes like email or tax numbers, surrogate keys use synthetic integer sequences (BIGINT IDENTITY), and UUIDs provide globally unique random or time-ordered identifiers. In high-throughput databases, sequential keys like BIGINT or UUIDv7 avoid B-tree page splits and index fragmentation caused by random UUIDv4 values.
FAQs
What happens when a 32-bit INT primary key runs out of numbers?
The database engine throws an integer overflow error, rejecting all subsequent insert operations until the column and all related foreign keys are migrated to BIGINT.
Why are random UUIDs bad for clustered indexes?
Random UUIDs cause B-tree leaf pages to split frequently because new keys insert into random positions, leading to index bloat and heavy disk I/O.
How does UUIDv7 differ from UUIDv4?
UUIDv7 includes a 48-bit millisecond timestamp at the beginning of the identifier, making it monotonically sequential while retaining random uniqueness.
Can I use an email address as a primary key?
It is strongly discouraged because users change emails. Use a surrogate key as the primary key and enforce uniqueness on the email column with a UNIQUE constraint.
Implement distributed locks and cron leader election in PostgreSQL using advisory locks. Compare session vs transaction locks and non-blocking try locks.
Discover 7 dangerous SQL anti-patterns that degrade query performance and corrupt results. Learn how to refactor non-SARGable predicates and NULL pitfalls.
Every relational database table requires a primary key to uniquely identify individual records and anchor foreign key relationships. The choice between natural keys, synthetic integer surrogate keys, and universally unique identifiers (UUIDs) is one of the most critical decisions in schema design.
Choosing poorly can degrade insert performance by an order of magnitude due to B-tree index fragmentation, leak business volume metrics through sequential numbers, or create schema migration nightmares when real-world attributes change. Selecting the right primary key pattern requires balancing physical storage efficiency with application architecture.
Natural keys: domain attributes as primary identifiers
A natural key is a column or set of columns that already exists in the real-world business domain and is guaranteed to be unique: an employee Social Security Number, a vehicle VIN, an ISO currency code, or a flight number. Check our guide to relational database schema design and normalization for normalization theory.
The primary benefit of a natural key is that it eliminates a synthetic column. When querying child tables, you do not need to join to the parent table to display the code. For example, if orders references currencies(currency_code), the order row already contains 'USD' or 'EUR', eliminating a lookup join.
Natural key definition and risks
-- Natural key schemaCREATE TABLE countries ( country_iso_code CHAR(2) PRIMARY KEY, -- e.g. 'US', 'CA', 'GB' country_name VARCHAR(100) NOT NULL);-- The natural key pitfall: what happens when business rules change?-- In 2020, North Macedonia changed its ISO code from MK to MKD.-- Updating a natural primary key cascades updates to millions of child rows!ALTER TABLE customer_addressesADD CONSTRAINT fk_addresses_countryFOREIGN KEY (country_iso_code) REFERENCES countries(country_iso_code)ON UPDATE CASCADE;
The fundamental flaw of natural keys is that real-world domain attributes change. Companies merge, tax identification formats update, and users change email addresses. Updating a primary key requires cascading updates across millions of foreign key references, creating massive transaction locks.
Surrogate integer keys: BIGINT and IDENTITY
A surrogate key is an artificial, monotonically increasing integer generated by the database sequence or identity column. It carries zero business meaning.
Surrogate integer key schema
-- Modern PostgreSQL standard identity columnCREATE TABLE customers ( customer_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email VARCHAR(255) NOT NULL UNIQUE, full_name VARCHAR(100) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now());
Surrogate keys offer three major performance advantages:
Compact storage: A BIGINT consumes only 8 bytes of storage, compared to 16 bytes for a UUID or 32+ bytes for a text natural key.
Sequential insertion: Because IDs increment monotonically, every new row is inserted into the rightmost leaf page of the clustered index B-tree, eliminating page splits.
Fast joins: CPU cache and memory controllers compare 64-bit integers much faster than variable-length strings.
In contrast, clustered storage in SQLite operates through 64-bit integer rowids as documented in the SQLite rowid table reference. However, sequential integers expose an enumeration vulnerability: competitors can scrape URLs like /orders/1042 to determine daily order volume and customer counts.
UUIDv4 vs UUIDv7: solving index fragmentation
Universally Unique Identifiers (UUIDs) allow distributed microservices and mobile clients to generate unique keys offline without coordinating with a central database. However, standard UUIDv4 identifiers are generated from random bits. Inserting random values into a B-tree index causes catastrophic fragmentation.
When you insert a random UUID, the key lands at an arbitrary location in the index. When a B-tree leaf page is full, the database must perform a page split: allocate a new 8KB page, copy half the rows, and update pointers. As tables grow larger than RAM, every insert requires random disk I/O to read and rewrite fragmented pages.
Comparing random UUIDv4 and sequential UUIDv7
-- Traditional random UUIDv4 (High B-tree fragmentation):-- 8c23a54d-17f2-4bc9-93ef-62a21e0586e3 -> Random location in index-- Modern time-ordered UUIDv7 (Monotonic insertion):-- 018c2b51-789a-7c22-b911-37d4f958a2d1 -> Sequential append at end of B-tree-- The first 48 bits encode a Unix timestamp in milliseconds!-- Creating a table using UUIDv7 in PostgreSQL 17 / extensions:CREATE TABLE telemetry_events ( event_id UUID PRIMARY KEY DEFAULT uuid_generate_v7(), device_id INT NOT NULL, recorded_at TIMESTAMPTZ NOT NULL);
As detailed in PostgreSQL UUID documentation, UUIDv7 combines a 48-bit Unix millisecond timestamp with random bits. This provides global uniqueness across distributed systems while preserving sequential B-tree append performance.
Comparison matrix: picking the optimal primary key
Choose your primary key architecture based on system requirements:
Lookup tables: Use natural keys for stable, immutable codes (ISO country codes, currency codes, HTTP status codes).
High-throughput internal tables: Use BIGINT GENERATED ALWAYS AS IDENTITY for high-velocity internal joins (ledger entries, inventory logs).
Public-facing entities: Use UUIDv7 or pair an internal BIGINT with a public UUID column to prevent ID enumeration attacks while maintaining fast internal foreign key joins.
Distributed multi-master systems: Use UUIDv7 to allow nodes to insert records independently without central ID generation bottlenecks.
Actionable checklist for primary key selection
Default to BIGINT: use 64-bit integers instead of 32-bit INT to avoid sequence exhaustion at 2.14 billion rows.
Avoid random UUIDv4: replace random UUIDv4 with sequential UUIDv7 to eliminate B-tree page splits on large tables.
Enforce natural uniqueness: when using surrogate keys, always place UNIQUE constraints on underlying business keys like email or account number.
Separate public and private keys: expose public UUIDs via APIs while keeping integer foreign keys for fast database joins.
Check foreign key column types: verify that foreign key columns match parent primary key data types exactly to prevent implicit type conversion.
Never use mutable keys: reject columns that can be updated as primary keys to avoid cascading foreign key updates.
Wrapping up
Choosing between natural keys, surrogate integers, and UUIDs shapes the long-term scalability and performance of your relational schema. Prioritize sequential, compact identifiers for high-write tables, and reserve natural keys for small, immutable reference datasets. When writing schema definitions, ensure your DDL statements adhere to team style rules by formatting your SQL with sqlfmt.