Sub topic 6
Identifying Rows with PRIMARY KEY
A primary key is the column, or set of columns, that identifies each row in a table. This chapter covers what the database enforces for you, how to declare simple and composite keys, how to choose a key, and the errors you will meet.
This chapter assumes you can write SELECT, INSERT, UPDATE, and DELETE, and that you have seen CREATE TABLE and NOT NULL. Examples use standard SQL and run in PostgreSQL. Dialect differences are noted where they matter.
What a primary key guarantees
A PRIMARY KEY constraint combines two rules:
- Unique: no two rows may have the same key value.
- Not null: no key column may be
NULL.
A table can have at most one primary key. Because the key is unique and never missing, you can always point at exactly one row with it. Other tables rely on this when they use a foreign key to refer to the row.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);Here customer_id is the primary key. You do not need to write NOT NULL next to it, because the primary key implies it. Writing it anyway is harmless.
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Ada Lovelace');The database generates customer_id through the identity column. The next chapter covers identity columns in detail.
What a rejected insert looks like
If you try to insert a key value that already exists, the database rejects the statement and leaves the table unchanged. The following example supplies the key by hand, which works for a table whose key is not GENERATED ALWAYS.
CREATE TABLE countries (
country_code CHAR(2) PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
INSERT INTO countries (country_code, name) VALUES ('NO', 'Norway');
INSERT INTO countries (country_code, name) VALUES ('NO', 'Norge');The second insert fails. In PostgreSQL the message looks like this:
ERROR: duplicate key value violates unique constraint "countries_pkey"
DETAIL: Key (country_code)=(NO) already exists.Two details are worth reading in that message. The constraint name countries_pkey was generated by the database because we did not name it. The DETAIL line names the column and the value that collided. Inserting NULL as the key fails with a different message, a not-null constraint violation on country_code.
Column-level and table-level declaration
You can declare a key in two places. The effect on a single-column key is the same.
-- Column-level
CREATE TABLE products (
product_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price NUMERIC(10, 2) NOT NULL CHECK (price >= 0)
);
-- Table-level, with an explicit name
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
total_amount NUMERIC(10, 2) NOT NULL,
CONSTRAINT pk_orders PRIMARY KEY (order_id),
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
ON DELETE RESTRICT,
CONSTRAINT ck_orders_total CHECK (total_amount >= 0),
CONSTRAINT ck_orders_status
CHECK (status IN ('new', 'paid', 'shipped', 'cancelled'))
);Use the table-level form when you want to name the constraint or when the key has more than one column. A composite key can only be written at table level.
Composite primary keys
A composite primary key uses two or more columns together. The combination must be unique, and every column in it must be non-null. Individual columns may repeat.
The classic case is a junction table, which links two tables in a many-to-many relationship. An order contains many products, and a product appears in many orders.
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders (order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (product_id)
);The key (order_id, product_id) means a product can appear only once per order. Adding the same product twice must instead raise its quantity.
| order_id | product_id | Allowed? | Reason |
|---|---|---|---|
| 1 | 10 | Yes | First row |
| 1 | 11 | Yes | Same order, different product |
| 2 | 10 | Yes | Same product, different order |
| 1 | 10 | No | Pair already exists |
| 1 | NULL | No | Key columns cannot be null |
The order of columns in a composite key matters for performance, not for uniqueness.Replace that note with the following callout, which states it in the required form:
Choosing a key: natural or surrogate
A natural key is a value that already identifies the thing in the real world, such as a country code or an ISBN. A surrogate key is a value with no meaning outside the database, such as a generated integer.
| Aspect | Natural key | Surrogate key |
|---|---|---|
| Meaning | Carries real-world meaning | Meaningless number or UUID |
| Stability | Can change (a person changes email, a code is reassigned) | Never needs to change |
| Size in foreign keys | Can be wide, repeated in every child row | Small and fixed |
| Uniqueness | You must trust the outside source | Guaranteed by the database |
A practical rule: use a surrogate key when no natural value is truly stable and unique. Keep the natural identifier too, and protect it with UNIQUE, as email is in the customers table. That gives you a stable key for joins and a rule that still blocks duplicate emails.
Keys should not change. An UPDATE of a key value is allowed, but every foreign key that references it must change too, or the update fails or cascades, depending on the referential action. Choosing a value that never changes avoids the problem.
Primary key versus UNIQUE
A primary key is close to UNIQUE NOT NULL, but there are differences.
| Feature | PRIMARY KEY | UNIQUE |
|---|---|---|
| Per table | At most one | Any number |
| Null values | Never allowed | Allowed in most systems (see below) |
| Default target of a foreign key | Yes, if no column list is given | No, must be named |
| Intent | The row's identity | An extra rule on a column |
Null handling in UNIQUE differs between systems. PostgreSQL and MySQL allow many nulls in a unique column because null is not equal to null. SQL Server allows only one null in a unique constraint. A primary key avoids the question, since nulls are never allowed.
How the key works internally
To enforce uniqueness quickly, the database creates a unique index on the key columns when you declare the constraint. Each insert checks that index for the new value. The same index makes lookups by key fast, such as WHERE customer_id = 42.
Some consequences follow from this:
- You do not need to create a separate index on the primary key. A second one only costs write time and disk space.
- In some systems the table is physically ordered by the key. In MySQL's InnoDB engine, rows are stored in primary key order, so a wide or random key makes the whole table and all its other indexes larger. In SQL Server the primary key is clustered by default.
- Dropping the primary key drops its index, and foreign keys that depend on it block the drop unless you remove them first.
Gotchas
- Tables without a key. Most databases allow a table with no primary key. You then cannot tell identical rows apart, and
UPDATEorDELETEon one of them touches every copy. Give every table a key. - Float and text keys. Floating-point numbers compare unreliably. Text keys depend on collation, so
'a'and'A'may or may not count as equal. Prefer integers, UUIDs, or short controlled codes. - Generated keys and gaps. Identity values are unique but not gapless. A rolled-back insert still uses a number. Never treat key values as a count of rows.
- Composite keys referenced by children. A child table needs every key column to reference the parent. Wide composite keys spread into every child table, which is a reason to prefer a surrogate key for a table that others reference.
- Adding a key later.
ALTER TABLE ... ADD PRIMARY KEYfails if the existing rows contain duplicates or nulls in the key columns. Clean the data first.
ALTER TABLE countries
DROP CONSTRAINT countries_pkey;
ALTER TABLE countries
ADD CONSTRAINT pk_countries PRIMARY KEY (country_code);The drop syntax differs by system. PostgreSQL, SQL Server, and standard SQL use DROP CONSTRAINT name. MySQL uses ALTER TABLE countries DROP PRIMARY KEY, because a MySQL primary key has no usable name.
Key points as a diagram
Exercise
A table enrollments links students to courses. A student may take many courses, a course has many students, and a student may enroll in a given course only once. Write the CREATE TABLE statement with a suitable primary key, assuming students(student_id) and courses(course_id) already exist. Then say what happens when the same pair is inserted twice.
Show answer
CREATE TABLE enrollments ( studentid INTEGER NOT NULL, courseid INTEGER NOT NULL, enrolledon DATE NOT NULL DEFAULT CURRENTDATE, PRIMARY KEY (studentid, courseid), FOREIGN KEY (studentid) REFERENCES students (studentid), FOREIGN KEY (courseid) REFERENCES courses (courseid) ); The composite key makes each (studentid, courseid) pair unique. The second insert of the same pair is rejected with a duplicate key error, and the table is unchanged.
Exercise
You run ALTER TABLE customers ADD PRIMARY KEY (email) on a table that already holds rows, and it fails. Name two data problems that could cause this, and say why email may still be a poor choice of primary key even if it succeeds.
Show answer
The failure comes from duplicate email values or from rows where email is NULL, since a primary key allows neither. Even when it succeeds, an email address can change, and then every foreign key row that references it must change too. It is also wider than an integer and is copied into every child table. A generated surrogate key with a UNIQUE constraint on email is the safer design.