Projetando chaves primárias e chaves substitutas
Aprenda como a escolha entre chaves naturais, chaves substitutas sequenciais e UUIDs afeta o tamanho do índice, o volume de inserções e o desempenho geral das consultas.
Projetando chaves primárias e chaves substitutas é uma aula grátis de PostgreSQL Performance & Query Optimization no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de PostgreSQL Performance & Query Optimization, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de PostgreSQL Performance & Query Optimization inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Natural vs Surrogate Keys
A natural key is a real-world attribute (e.g. email). A surrogate key is a meaningless generated value (e.g. an integer id). Surrogate keys stay stable even when business data changes.
Why Key Choice Affects Performance
The primary key is referenced by every foreign key and many indexes. A wide key bloats all of those structures, increasing disk usage and cache pressure. Narrow keys keep indexes small and fast.
Sequential Integer Keys
The classic choice is a monotonically increasing integer. New rows append to the end of the B-tree, minimizing page splits and keeping inserts fast.
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
total NUMERIC
);IDENTITY vs serial
Prefer the SQL-standard GENERATED ALWAYS AS IDENTITY over the older serial pseudo-type. It is cleaner and avoids ownership quirks with the underlying sequence.
The UUID Temptation
UUIDs are great for distributed systems because clients can generate them. But random UUIDs (v4) scatter inserts all over the index, causing page splits and poor cache locality.
CREATE TABLE events (
id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
payload JSONB
);Time-Ordered UUIDs
If you need UUIDs, prefer a time-ordered variant (UUIDv7) so values increase roughly with time. This restores the append-friendly behavior of sequential keys while keeping global uniqueness.
Key Width Matters
A BIGINT is 8 bytes; a UUID is 16 bytes. Every secondary index stores the primary key, so wider keys multiply storage across all of them. Measure the impact.
SELECT pg_size_pretty(pg_relation_size('orders_pkey'));Composite Primary Keys
Sometimes the natural key spans two columns, such as (order_id, line_no) in a detail table. Keep composite keys narrow and put the most selective column first.
CREATE TABLE order_lines (
order_id BIGINT,
line_no INT,
PRIMARY KEY (order_id, line_no)
);Foreign Keys Inherit the Cost
Every child row stores a copy of the parent key. A 16-byte UUID parent key makes a million-row child table 8 MB larger than an 8-byte integer would. Multiply by every referencing table.
Choosing in Practice
Guidelines:
- Default to BIGINT IDENTITY for single-database apps
- Use time-ordered UUIDs when clients must generate ids or you shard
- Avoid random v4 UUIDs as primary keys on hot insert paths
- Keep composite natural keys short
Indexing the Foreign Key Side
Whatever key you pick, always index the child's foreign key column. Without it, deleting or updating a parent forces a full scan of the child table to check references.
CREATE INDEX idx_order_lines_order
ON order_lines (order_id);Quick Check
Test your key-design knowledge.
Recap
You learned key design for performance:
- Surrogate keys stay stable; natural keys can change
- Narrow keys shrink every index and foreign key
- Sequential BIGINT IDENTITY inserts are cheap
- Random v4 UUIDs scatter inserts; prefer time-ordered UUIDs
- Keep composite keys short and selective-first
Aprenda SQL com um tutor de IA — grátis
Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.
- Cursos
- 22
- Aulas
- 88
Perguntas Frequentes
A aula “Projetando chaves primárias e chaves substitutas” é grátis?
Sim — o texto completo de “Projetando chaves primárias e chaves substitutas” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de PostgreSQL Performance & Query Optimization, atualize para CoddyKit PRO. O curso de PostgreSQL Performance & Query Optimization inclui 4 aulas no total.
O que vou aprender em “Projetando chaves primárias e chaves substitutas”?
Aprenda como a escolha entre chaves naturais, chaves substitutas sequenciais e UUIDs afeta o tamanho do índice, o volume de inserções e o desempenho geral das consultas. Você pratica PostgreSQL Performance & Query Optimization com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar PostgreSQL Performance & Query Optimization?
Nenhuma experiência prévia é necessária. PostgreSQL Performance & Query Optimization no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Projetando chaves primárias e chaves substitutas”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de PostgreSQL Performance & Query Optimization?
Sim. Cada aula de PostgreSQL Performance & Query Optimization inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Concessões entre normalização e desnormalização
- Escolhendo tipos de dados adequados
- Particionamento de tabelas grandes
- Projetando chaves primárias e chaves substitutas