DAT-3Recommended
Give every row a stable key
Give every table a primary key that never changes. Never use a value people can edit, such as an email or a name, as the key.
How to do it
Use a generated bigint or a UUID as the primary key. A 32-bit int runs out at about 2.1 billion rows, and widening it later locks the table. Keep natural identifiers as separate UNIQUE columns, so a customer can change their email without breaking references. Prefer UUID version 7 (RFC 9562) over random version 4, because time-ordered keys keep indexes compact. PostgreSQL 18 has uuidv7() built in, and most languages have a library for older versions. For people, keep your own user ID instead of the sign-in provider's.
Examples
SQL example
-- PostgreSQL: tables without a primary key, expect no rows
SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r' AND n.nspname = 'public'
AND NOT EXISTS (SELECT 1 FROM pg_constraint k WHERE k.conrelid = c.oid AND k.contype = 'p');
How to check
A catalog query finds no table without a primary key, and every generated key is bigint or a UUID. A search of the code finds no UPDATE that sets a key column.
Sources
Related rules
- API-9 Send IDs as strings in API design
- ACC-7 Keep your own user ID in Accounts and identity
- APP-38 Key rows by their ID in Web app interface
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/schema-design/stable-keys">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.