Sub topic 3
Defining a primary key
This chapter assumes you can write basic SELECT, INSERT, UPDATE, and DELETE statements. It also assumes you can create tables with CREATE TABLE and know what NULL means. Examples use PostgreSQL syntax.
What a primary key guarantees
A primary key is a column, or a set of columns, that identifies each row in a table. The database enforces two rules on it:
- Unique. No two rows may have the same key value.
- Not null. Every row must have a value. A missing value is rejected.
A primary key is a UNIQUE constraint plus NOT NULL, with one extra property: a table can have at most one of them. Other tables can then point at the key to refer to a specific row. That is how foreign keys work, and a later chapter covers them.
Without a key, a table can hold two identical rows. You then cannot update or delete just one of them, because no condition separates them. Every table should have a primary key, including small lookup tables and junction tables.
Declaring a primary key
You can declare a single-column key inline, next to the column definition:
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);Here customer_id is the primary key. The database generates its values (see the chapter on generating key values). The email column is not the primary key, but it is still unique, so no two customers can share an address.
You can also declare the key as a table constraint, after the columns:
CREATE TABLE countries (
country_code CHAR(2) NOT NULL,
name VARCHAR(100) NOT NULL,
CONSTRAINT pk_countries PRIMARY KEY (country_code)
);The table-level form has three advantages:
- It is the only way to declare a composite key, a key built from several columns.
- It lets you name the constraint, here
pk_countries. Error messages and laterALTER TABLEstatements then use a name you chose. - It keeps all constraints in one place.
If you leave the name out, PostgreSQL generates one, usually tablename_pkey. The generated names differ between databases.
How the database enforces it
When you declare a primary key, the database creates a unique index on the key columns. Each INSERT or UPDATE that touches those columns checks the index for a duplicate. The same index makes lookups by key fast.
The checks produce errors like these:
INSERT INTO countries (country_code, name) VALUES ('DE', 'Germany');
INSERT INTO countries (country_code, name) VALUES ('DE', 'Deutschland');
-- ERROR: duplicate key value violates unique constraint "pk_countries"
INSERT INTO countries (country_code, name) VALUES (NULL, 'Nowhere');
-- ERROR: null value in column "country_code" violates not-null constraintThe same rules apply to UPDATE. Changing a key value to one that already exists fails, and so does setting a key column to NULL.
Candidate keys and the primary key
A table can have several columns, or column sets, that could each identify a row. These are candidate keys. In customers, both customer_id and email qualify. You pick one candidate as the primary key. The others remain as alternate keys, declared with UNIQUE NOT NULL.
| Property | PRIMARY KEY | UNIQUE |
|---|---|---|
| Duplicates allowed | No | No |
| NULL allowed | No | Yes in most databases (see below) |
| How many per table | One | Many |
| Default target of a foreign key | Yes | Only if named explicitly |
A foreign key that omits the column list references the parent's primary key. A foreign key can also reference a UNIQUE column if you name it.
Behavior with NULL differs for UNIQUE. PostgreSQL treats NULLs as distinct, so a UNIQUE column can hold many NULLs. SQL Server allows only one NULL in a UNIQUE column. This is one reason to add NOT NULL to alternate keys unless you want optional values.
Choosing the key columns
A good primary key has these properties:
- Unique. It is unique for every row, always, and not just in the data you have today.
- Stable. Its value never changes. Foreign keys copy the value into other tables, so changing it means updating every referencing row, or having the update rejected.
- Present. It is known when the row is created.
- Compact. It is small, because the key is copied into every referencing table and every index entry.
Real-world identifiers often fail the stability test. Email addresses change, names change, and phone numbers get reassigned. Even identifiers that seem permanent, such as national ID numbers, can be missing, mistyped, or reissued. The next chapter compares natural and surrogate keys in detail. A common compromise is a generated integer as the primary key, plus a UNIQUE constraint on the natural identifier, as in customers above.
A stable natural code can make a good key. The country_code example works because ISO country codes are short, fixed, and meaningful to people reading the data.
Adding a key to an existing table
If you forgot the key, you can add one later:
ALTER TABLE countries
ADD CONSTRAINT pk_countries PRIMARY KEY (country_code);This fails if the column already contains duplicates or NULLs. Find the duplicates first:
SELECT country_code, COUNT(*)
FROM countries
GROUP BY country_code
HAVING COUNT(*) > 1;Fix or remove those rows, then rerun the ALTER TABLE. On a large table, adding a key builds an index and can lock the table while it runs. Plan it for a quiet period.
Common errors
- No key at all. The table accepts exact duplicates, and you cannot target one row safely.
- A key that can change. Using an email address or username as the key forces cascading updates when it changes.
- Meaning packed into the key. A key like
2026-NY-00042encodes year and region. When the meaning changes, the key is wrong but cannot be changed cheaply. - A key that is too wide. A long text key is copied into every foreign key column and every index.
- Forgetting alternate keys. If you use a generated id as the primary key, the natural identifier still needs a UNIQUE constraint. Otherwise duplicate customers with the same email can exist.
- Reusing key values. If you delete a row and give its key to a new row, old references elsewhere, such as logs or exports, point at the wrong thing. Generated keys avoid this.
Exercises
Exercise
A table employees has columns employee_id, ssn, and email. All three are unique and never NULL. Which are candidate keys, and what do you do with the ones you do not pick as the primary key?
Show answer
All three are candidate keys. Pick one as the primary key, preferably a stable, compact one such as a generated employee_id. Declare the other two with UNIQUE NOT NULL so they stay alternate keys and the database still rejects duplicates.
Exercise
Write a statement that adds a primary key named pk_products on the column sku of an existing table products. What must be true of the existing data for it to succeed?
Show answer
ALTER TABLE products ADD CONSTRAINT pk_products PRIMARY KEY (sku); The sku column must contain no duplicate values and no NULLs.