Sub topic 3
Primary keys and identity columns
This chapter assumes you can write basic SELECT, INSERT, UPDATE, and DELETE statements. It also assumes you have PostgreSQL 12 or newer and can run SQL in psql or another client. The tables are the ones the earlier chapters sketched: authors, books, and the join table book_authors.
What a primary key guarantees
A primary key is the column (or set of columns) that identifies exactly one row in a table. PostgreSQL enforces three things for you:
- Every value is unique within the table.
- No value is
NULL. - A table has at most one primary key.
Behind the scenes, PostgreSQL creates a unique B-tree index to enforce the rule. That index also makes lookups by key fast. You can see the indexes it created:
CREATE TABLE authors (
author_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE books (
book_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
isbn13 char(13) UNIQUE CHECK (isbn13 ~ '^[0-9]{13}$'),
published_year smallint CHECK (published_year BETWEEN 1400 AND 2100),
page_count integer CHECK (page_count > 0)
);
SELECT indexname
FROM pg_indexes
WHERE tablename = 'books'
ORDER BY indexname;The query returns books_isbn13_key and books_pkey. The UNIQUE constraint on isbn13 and the primary key each get their own index. PostgreSQL names the primary key constraint <table>_pkey unless you name it yourself with CONSTRAINT name PRIMARY KEY. Those names appear in error messages, so they are useful to recognize.
Surrogate keys and natural keys
A natural key is a value that already exists in the real world and identifies the thing, such as an ISBN. A surrogate key is a value the database invents only to identify the row. This schema uses surrogate keys (book_id, author_id) and keeps the ISBN as a separate UNIQUE column. The reasons:
- Not every book has an ISBN. Older books and self-published items often lack one. A primary key can never be
NULL, but aUNIQUEcolumn can holdNULL. - Natural values get corrected. If you fix a mistyped ISBN, every foreign key that points to it would have to change too. A surrogate key never changes.
- Authors have no natural key at all. Two different people can share a name.
- Narrow keys are cheap. A
bigintis 8 bytes. Every foreign key column and index entry that refers to the row repeats it.
The trade-off is that a surrogate key does not prevent duplicate real-world entries. Nothing stops you from inserting the same book twice under two book_id values. That is why the UNIQUE constraint on isbn13 still matters. Chapter 4 covers it in more detail.
Identity columns
GENERATED ALWAYS AS IDENTITY tells PostgreSQL to fill the column from an internal sequence. A sequence is a counter object that hands out increasing numbers. Each insert that omits the column gets the next number.
INSERT INTO authors (name) VALUES ('Ursula K. Le Guin') RETURNING author_id;
INSERT INTO authors (name) VALUES ('Octavia E. Butler') RETURNING author_id;RETURNING sends the generated key back to you in the same statement. You will need that to link related rows without a second query.
ALWAYS versus BY DEFAULT
| Form | Explicit value in INSERT | Typical use |
|---|---|---|
| `GENERATED ALWAYS AS IDENTITY` | Rejected unless you add `OVERRIDING SYSTEM VALUE` | Keys that only the database should assign |
| `GENERATED BY DEFAULT AS IDENTITY` | Accepted | Loading data that already has keys |
With ALWAYS, a stray explicit value is an error instead of a silent collision:
INSERT INTO authors (author_id, name) VALUES (100, 'Hand-numbered Author');ERROR: cannot insert a non-DEFAULT value into column "author_id"
DETAIL: Column "author_id" is an identity column defined as GENERATED ALWAYS.
HINT: Use OVERRIDING SYSTEM VALUE to override.This guard is the reason to prefer ALWAYS in a schema like this one. Application code cannot invent keys that later clash with the sequence.
Identity versus serial
Older tutorials use serial or bigserial. Those are shorthand that creates a sequence and sets a column default, but the sequence is a loosely attached, separate object. Identity columns, available since PostgreSQL 10, tie the sequence to the column. They follow the SQL standard, and they are dropped with the table. In new schemas, use identity.
Gaps are normal
A sequence never gives a number back. If an insert is rolled back, or fails a constraint, the number it used is gone:
BEGIN;
INSERT INTO authors (name) VALUES ('Rolled Back Author');
ROLLBACK;
INSERT INTO authors (name) VALUES ('Kept Author') RETURNING author_id;The second author_id skips a value. Sequences work this way so that concurrent sessions never wait on each other for numbers.
Loading data that already has keys
Suppose you import authors from another system with their own ids. ALWAYS rejects them unless you override it. After an override, the sequence does not know about the imported numbers, and the next generated key can collide with one of them. Reset the sequence afterward:
INSERT INTO authors (author_id, name) OVERRIDING SYSTEM VALUE
VALUES (500, 'Imported Author');
SELECT setval(
pg_get_serial_sequence('authors', 'author_id'),
(SELECT max(author_id) FROM authors)
);pg_get_serial_sequence finds the sequence behind the column, and setval moves it to the highest key in use. The next insert gets max + 1. If you skip this step, you will eventually see duplicate key value violates unique constraint "authors_pkey" on an insert that did not specify a key. That error is the usual sign of an unsynchronized sequence.
If you do this often, switch the column with ALTER TABLE authors ALTER COLUMN author_id SET GENERATED BY DEFAULT;. Switching back to ALWAYS later is the same command with ALWAYS.
Composite primary keys
A primary key can span several columns. In book_authors, a row is identified by the pair of book and author:
CREATE TABLE book_authors (
book_id bigint NOT NULL REFERENCES books (book_id) ON DELETE CASCADE,
author_id bigint NOT NULL REFERENCES authors (author_id) ON DELETE RESTRICT,
author_position smallint NOT NULL DEFAULT 1,
PRIMARY KEY (book_id, author_id)
);No surrogate key is needed here. The pair is already unique by meaning, and a second link between the same book and author is an error:
ERROR: duplicate key value violates unique constraint "book_authors_pkey"Column order in a composite key matters for speed. The index on (book_id, author_id) serves lookups by book_id alone, or by both columns. It does not efficiently serve lookups by author_id alone. That is why a later chapter adds a separate index on author_id.
Choosing the key type
bigintidentity is the default choice. It costs 4 bytes more thanintegerper key and per reference, and in return you never need to migrate a column that ran out of values (about 2.1 billion forinteger).integeris acceptable for small, bounded lookup tables, but changing it later means rewriting the table and every column that references it.uuidhelps when several systems must create keys without coordination. Random UUIDs are 16 bytes and insert at random positions in the index, which is slower than increasing integers. A personal book tracker does not need them.
Common mistakes
- Inserting explicit keys into a
GENERATED ALWAYScolumn and then not knowing how to override it. - Forgetting
setvalafter an import, then hittingauthors_pkeyduplicates later. - Treating the key as meaningful: sorting by it to mean "most recently read," for example. Store a date for that.
- Using
serialin new code, or making a column bothserialand identity. - Using a mutable value such as a title as the primary key.
Exercise
You import 200 books with ids 1 to 200 into a table whose book_id is GENERATED ALWAYS AS IDENTITY, using OVERRIDING SYSTEM VALUE. The next ordinary insert fails with duplicate key value violates unique constraint "books_pkey". Why did it happen, and what statement fixes it?
Show answer
The import supplied its own keys, so the identity sequence never advanced. It still hands out 1, which already exists. Move the sequence past the highest key with SELECT setval(pg_get_serial_sequence('books', 'book_id'), (SELECT max(book_id) FROM books));.
Exercise
A reading entry in readings is rolled back, and the next entry gets reading_id 8 instead of 7. Is something wrong? Would a composite primary key on book_authors show the same gaps?
Show answer
Nothing is wrong. A sequence does not return numbers used by rolled-back or failed inserts, so gaps are normal. book_authors has no sequence, because its key is the pair of book_id and author_id, so it cannot have this kind of gap.