Проектирование первичных и суррогатных ключей
Узнайте, как выбор между естественными ключами, последовательными суррогатными ключами и UUID влияет на размер индекса, скорость вставки и общую производительность запросов
«Проектирование первичных и суррогатных ключей» — бесплатный урок PostgreSQL Performance & Query Optimization на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения PostgreSQL Performance & Query Optimization, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс PostgreSQL Performance & Query Optimization содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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
Часто задаваемые вопросы
Урок «Проектирование первичных и суррогатных ключей» бесплатный?
Да — полный текст урока «Проектирование первичных и суррогатных ключей» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс PostgreSQL Performance & Query Optimization, подпишись на CoddyKit PRO. Курс PostgreSQL Performance & Query Optimization содержит 4 уроков всего.
Чему я научусь в уроке «Проектирование первичных и суррогатных ключей»?
Узнайте, как выбор между естественными ключами, последовательными суррогатными ключами и UUID влияет на размер индекса, скорость вставки и общую производительность запросов Ты практикуешь PostgreSQL Performance & Query Optimization с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать PostgreSQL Performance & Query Optimization?
Предыдущий опыт не требуется. PostgreSQL Performance & Query Optimization на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Проектирование первичных и суррогатных ключей»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке PostgreSQL Performance & Query Optimization?
Да. Каждый урок PostgreSQL Performance & Query Optimization включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Компромиссы нормализации и денормализации
- Выбор подходящих типов данных
- Секционирование больших таблиц
- Проектирование первичных и суррогатных ключей