Sub topic 1
Why tables need generated IDs
Almost every table you design needs a way to point at exactly one row. This chapter explains why many designs give each row a number that the database generates, what that number is for, and what it does not guarantee. Later chapters cover the PostgreSQL syntax that produces the number.
Prerequisites
This chapter assumes you already know:
- Basic SQL:
CREATE TABLE,INSERT,SELECT, andUPDATE. - What a primary key is, and that a foreign key refers to one.
- The integer types
smallint,integerandbigint. - The basic idea of a transaction: changes are either committed or rolled back.
You can run every example in psql against any recent PostgreSQL version (10 or later) in a scratch database.
What a row identifier has to do
A relational database finds, updates and links rows by value. Other tables refer to a row through a foreign key, and applications refer to it in URLs, logs and API calls. So the identifier of a row must meet four requirements:
- Unique. No two rows share the same value.
- Present. Every row has a value, never
NULL. - Stable. The value does not change for the life of the row, because everything that refers to the row stores a copy of it.
- Compact. The value is small, because it is copied into every foreign key column and every index that refers to the row.
A primary key constraint enforces the first two requirements. The last two are design choices, and they are where the trouble starts.
The trouble with natural keys
A natural key is a value that already exists in your data and identifies the row in the real world. Examples are an email address, a passport number, or a product code. Natural keys look attractive because they need no extra column. In practice they often fail the stability and compactness requirements.
| Candidate natural key | Typical problem |
|---|---|
| Email address | Users change addresses. Case and whitespace differences create near-duplicates. |
| National ID or tax number | Sensitive data that you would copy into many tables. Some people do not have one yet. |
| Product code | The supplier renames or reuses codes. |
| Name plus birth date | Not unique. Two people can share both. |
| Phone number | Reassigned to other people. Formats vary. |
The stability problem is easy to see. This schema uses an email address as the primary key and refers to it from another table.
CREATE TABLE customers_natural (
email text PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE orders_natural (
order_no text PRIMARY KEY,
customer_email text NOT NULL
REFERENCES customers_natural (email) ON UPDATE CASCADE,
total_cents integer NOT NULL
);
INSERT INTO customers_natural VALUES ('[email protected]', 'Ada');
INSERT INTO orders_natural VALUES ('A-1', '[email protected]', 1500);
UPDATE customers_natural
SET email = '[email protected]'
WHERE email = '[email protected]';When Ada changes her address, PostgreSQL has to rewrite the matching row in every table that refers to her. Here that is one row, but in a real system it could be millions of rows across many tables. Without ON UPDATE CASCADE the update fails outright. Any external system that stored the old email, such as a payment provider or a bookmarked URL, silently stops matching.
Surrogate keys
A surrogate key is a value created only to identify the row. It has no meaning in the business domain. It is not a name, a date, or a code anyone reads out loud. Because nothing about the real world is encoded in it, nothing in the real world can force it to change.
An auto-incrementing ID is the most common surrogate key: a whole number that starts small and grows by one for each new row. The application does not choose it. The database fills it in at insert time. This is the same design, using a surrogate key, with the natural value demoted to an ordinary column:
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
name text NOT NULL
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id),
placed_at timestamptz NOT NULL DEFAULT now()
);The GENERATED ALWAYS AS IDENTITY clause is the subject of the next chapters. For now, read it as "PostgreSQL supplies this value on insert." Notice what changed:
ordersrefers tocustomers.id, a number that never changes. Changing an email touches exactly one row in one table.emailis stillUNIQUE, so the business rule "one account per address" is still enforced. The surrogate key does not replace that rule. It sits beside it.- A
biginttakes 8 bytes. An email address is variable length, often 20 or more bytes. Every foreign key column and every index entry that refers to the row gets smaller.
Where the number comes from
You could generate the number in your application, for example by running SELECT max(id) + 1 before each insert. Do not do this. Two sessions can read the same maximum at the same moment, and both then try to insert the same ID. Fixing that needs locking, and locking makes every insert wait for the one before it.
PostgreSQL solves this with a sequence, a special database object that hands out numbers without waiting for transactions to finish. The next chapter covers sequences in detail. An identity column is a column that is wired to its own sequence automatically.
The design question for this chapter is simpler: should this table have a generated number at all? The sections below give the criteria.
What a generated ID does not give you
A surrogate key solves a specific problem. Teams get into trouble when they expect more from it.
- It does not stop duplicate business data. Without the
UNIQUEconstraint onemail, you can insert the same customer twice and get two different IDs. Keep a unique constraint on the natural identifier whenever one exists. - It is not a count of rows. After deletes and rolled-back inserts the largest ID is higher than the number of rows. A later chapter explains why gaps appear.
- It is not a reliable creation order. IDs are issued in increasing order, but concurrent transactions commit in a different order than they got their numbers. If you need "when was this created," store a timestamp.
- It is not secret. Sequential numbers let anyone who sees
/orders/1042guess that/orders/1043exists. Check authorization on every request. If the number itself should not reveal volume or growth rate, a different key type may fit better (see the last section of this tutorial). - It is not unique by itself. The generated value only comes from a counter. The uniqueness guarantee comes from the primary key or unique constraint you place on the column.
Deciding whether a table needs one
Most tables get a surrogate key. A few do not. Use these questions in order.
- Is there a short, stable value that is guaranteed unique and that you control? A country code from ISO 3166 (such as
NZ) is a typical case. A natural key is fine here. - Is the table a pure link between two others, such as a
student_coursestable? A composite primary key of the two foreign keys is usually enough, with no extra ID. - Will other tables, files or external systems refer to rows of this table? If yes, they need a stable, compact handle. Use a surrogate key.
- Is the natural identifier sensitive, long, or subject to correction? Use a surrogate key.
If you are unsure, add a surrogate key and keep a unique constraint on the natural identifier. The cost is one small column and one index. The cost of removing an unstable natural key later is a migration across every referencing table.
Common mistakes
- Using the surrogate key as the only constraint, and so allowing duplicate business rows.
- Choosing a type that is too small. A
smallintID overflows at 32,767 rows. A later chapter covers sizing. - Computing IDs with
max(id) + 1in application code. - Treating the ID order as the business order of events.
Exercise
A products table uses sku text PRIMARY KEY. The supplier announces it will rename all SKUs next month, and six other tables have foreign keys to products.sku. Describe how you would redesign the key, and name the constraint you must keep so that duplicate products stay impossible.
Show answer
Add a generated numeric surrogate key, for example id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, and change the six referencing tables to hold product_id foreign keys that point at it. Keep sku as an ordinary text NOT NULL column with a UNIQUE constraint. The SKU rename then updates one column in one table, the foreign keys are unaffected, and the unique constraint still prevents two products with the same SKU.
Exercise
Name two things a generated auto-incrementing ID does not guarantee, and say what you would use instead for each.
Show answer
It does not guarantee a gapless sequence, because rolled-back inserts and deletes leave gaps, so use a separate, purpose-built column if customers need gapless numbers. It does not guarantee creation order or uniqueness of business data, so use a timestamp column such as placed_at for ordering and a UNIQUE constraint on the natural identifier (for example email) for duplicates.