Sub topic 6
Primary keys: identifying each row
This chapter assumes you can read basic CREATE TABLE and INSERT statements and know that a table holds rows and columns. It covers what a primary key guarantees, how to choose one, how composite keys work, and the mistakes that cause trouble later.
Why every row needs an identity
A table is a set of rows. If two rows can be completely identical, you cannot say which one you mean when you update or delete one of them, and no other table can reliably point at one of them. A primary key is a column, or a group of columns, whose values identify each row in the table.
A primary key enforces three rules:
- Unique. No two rows have the same key value.
- Not null. Every row has a key value.
- Stable. This is a design rule, not something the database enforces. The value should not change after the row is created, because other tables will store copies of it.
A table has at most one primary key. It can have other columns that are also unique, but only one is declared the primary key.
Declaring a primary key
You declare the key in CREATE TABLE. This example is runnable in any common RDBMS, which is relational database management system software such as PostgreSQL, MySQL, or SQLite.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
INSERT INTO products (product_id, name) VALUES (1, 'Keyboard');
INSERT INTO products (product_id, name) VALUES (2, 'Mouse');
-- Rejected: product_id 1 already exists.
INSERT INTO products (product_id, name) VALUES (1, 'Monitor');The third statement fails. In PostgreSQL the message is duplicate key value violates unique constraint "products_pkey". The row is not stored, and the two earlier rows are unchanged. The database enforces the rule, so your application code cannot forget to check it.
A key is also what makes a single row addressable:
SELECT name FROM products WHERE product_id = 2;This query returns at most one row, because the key is unique.
What the database does behind the scenes
When you declare a primary key, the database creates a unique index on those columns. An index is a lookup structure that finds a value without reading the whole table. The index serves two purposes:
- It checks uniqueness quickly on every insert and update.
- It makes lookups by key fast.
Because of this, you do not need to run CREATE INDEX on a primary key column. A later chapter covers indexes in general. Remember here that the index comes with the key, and that it adds a small cost to each write.
Primary keys and foreign keys
A foreign key is a column in one table that stores the primary key value of a row in another table. The primary key is the target that foreign keys point to, so key choices affect every table that references it.
If you changed a customer's customer_id, every order that references it would need to change too, or the database would reject the change. This is the main reason keys should be stable.
Natural keys and surrogate keys
You have two options for what to use as a key.
A natural key is a value that already exists in the real world and identifies the thing, such as an ISBN for a book or a country code for a country. A surrogate key is a value invented only for the database, such as an auto-incrementing integer or a UUID. It has no business meaning.
| Property | Natural key | Surrogate key |
|---|---|---|
| Meaning | Carries real information | None |
| Stability | Can change when the real world changes | Never needs to change |
| Size | Often long text or several columns | Usually one small integer or UUID |
| Risk | Rules may be wrong or may change | Duplicate real-world rows are not detected unless you add `UNIQUE` |
Most application tables use a surrogate key. The customers table from this tutorial shows the usual pattern: a surrogate customer_id as the primary key, plus a UNIQUE constraint on email so the real-world identifier stays unique too.
Email addresses look like natural keys, but people change them. A key that changes forces updates across every referencing table. Names are worse, because many people share one. Even identifiers that sound official, such as national ID numbers, can be missing, mistyped, or reassigned. Use them as ordinary columns with constraints, not as keys.
Natural keys do work well when the value is controlled by a standard and almost never changes. A table of ISO currency codes can reasonably use currency_code CHAR(3) PRIMARY KEY.
Generating surrogate key values
Writing key values by hand is error-prone, so databases generate them. The syntax differs by system:
| System | Declaration |
|---|---|
| PostgreSQL | `customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY` |
| MySQL | `customer_id INTEGER AUTO_INCREMENT PRIMARY KEY` |
| SQLite | `customer_id INTEGER PRIMARY KEY` (assigns a value automatically when you omit it) |
Here is the PostgreSQL form in use:
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
);
INSERT INTO customers (name, email)
VALUES ('Ada Lovelace', '[email protected]'),
('Grace Hopper', '[email protected]');
SELECT customer_id, name FROM customers ORDER BY customer_id;The database assigns 1 and 2. You omit customer_id from the insert, so two sessions inserting at the same time never pick the same value.
Generated values have two properties that surprise people:
- Gaps are normal. If an insert fails or a transaction rolls back, the number it consumed is usually not reused. Do not use the key to count rows, and do not treat a gap as missing data.
- Order is not time. Do not rely on the key to sort rows by creation time. Store a
created_atcolumn when you need that.
A UUID key avoids a central counter and makes values hard to guess, but it takes more space (16 bytes against 4 for a standard integer) and gives less compact indexes. Choose an integer unless you need ids created outside the database, for example by several systems that later merge.
Composite primary keys
Sometimes no single column identifies a row, but a combination does. A composite primary key is a primary key made of two or more columns. The junction table for a many-to-many relationship is the standard case:
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
product_id INTEGER NOT NULL REFERENCES products (product_id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id)
);The rule applies to the pair. Order 100 can contain product 1 and product 2, and product 1 can appear in orders 100 and 101. The database rejects a second row with the pair (100, 1). That is the desired behavior: a product appears once per order, with a quantity, instead of as repeated rows.
Each column in a composite key is also individually non-null. The column order matters for the index: the index on (order_id, product_id) is fast for lookups by order_id alone, but not for lookups by product_id alone. If you often search by product_id, add a separate index on it.
Some teams give junction tables their own surrogate id and add a UNIQUE (order_id, product_id) constraint instead. Both designs are valid. The composite key is smaller and states the rule directly. A surrogate key is easier when other tables must reference individual junction rows.
Common errors and gotchas
- Choosing a changeable value. If you must update a key, you must also update every foreign key that holds it. Pick values that will not change.
- Reusing deleted keys. If a key value is deleted and later given to a new row, old references elsewhere, such as logs, exports, or caches, may point to the wrong thing. Let generators keep counting.
- Forgetting the real-world uniqueness rule. A surrogate key makes every row unique, even when you insert the same customer twice. Add
UNIQUEon the columns that must be unique in the real world. - Assuming
NULLis rejected everywhere. The standard requires a primary key column to be non-null, and PostgreSQL and MySQL enforce it. SQLite has a historical exception: a primary key column that is not declaredINTEGERcan containNULLunless you addNOT NULL. DeclareNOT NULLexplicitly if the table might run on SQLite. - Overly wide keys. Every table that references the key repeats it, and every index that includes it stores it. A long text key multiplies storage.
- Tables without a key. The database allows them, but you cannot reliably update or delete a single row, and duplicates accumulate. Give every table a primary key.
Exercise
A students table uses email as its primary key. A student changes their email address, and enrollments.student_email references it. Describe the problem and give a better design.
Show answer
Changing the key value means every row in enrollments that holds the old email must change too, or the update is rejected, depending on the foreign key's rules. The key was not stable. A better design adds student_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY to students, keeps email VARCHAR(255) NOT NULL UNIQUE, and has enrollments store student_id. Email changes then touch only one row.
Exercise
In order_items, the primary key is (order_id, product_id). A customer wants to buy the same product twice in one order, once as a gift. What happens if you insert a second row for the same pair, and how would you handle it?
Show answer
The database rejects the insert with a duplicate key error, because the pair already exists. Either update the quantity on the existing row, or, if the two lines must stay separate, redesign the table with a surrogate order_item_id primary key and, optionally, a gift flag column that is part of a UNIQUE constraint.