PostgreSQL Performance & Query Optimization · Lección

Diseño de claves primarias y claves sustitutas

Aprenda cómo la elección entre claves naturales, claves sustitutas secuenciales y UUID afecta al tamaño de los índices, al rendimiento de inserción y al rendimiento general de las consultas.

Lección 4 de 413 pasos

Diseño de claves primarias y claves sustitutas es una lección gratuita de PostgreSQL Performance & Query Optimization en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de PostgreSQL Performance & Query Optimization, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de PostgreSQL Performance & Query Optimization incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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
Gratis para empezar

Aprende SQL con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
22
Lecciones
88

Preguntas frecuentes

¿La lección «Diseño de claves primarias y claves sustitutas» es gratis?

Sí — el texto completo de «Diseño de claves primarias y claves sustitutas» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de PostgreSQL Performance & Query Optimization, actualiza a CoddyKit PRO. El curso de PostgreSQL Performance & Query Optimization incluye 4 lecciones en total.

¿Qué aprenderé en «Diseño de claves primarias y claves sustitutas»?

Aprenda cómo la elección entre claves naturales, claves sustitutas secuenciales y UUID afecta al tamaño de los índices, al rendimiento de inserción y al rendimiento general de las consultas. Practicas PostgreSQL Performance & Query Optimization con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar PostgreSQL Performance & Query Optimization?

No se requiere experiencia previa. PostgreSQL Performance & Query Optimization en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Diseño de claves primarias y claves sustitutas»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de PostgreSQL Performance & Query Optimization?

Sí. Cada lección de PostgreSQL Performance & Query Optimization incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Equilibrio entre normalización y desnormalización
  2. Elección de tipos de datos adecuados
  3. Particionado de tablas grandes
  4. Diseño de claves primarias y claves sustitutas
← Volver a PostgreSQL Performance & Query Optimization