Sub topic 3
Defining a Primary Key
Assume you know how to create tables and use SELECT, INSERT, UPDATE, and DELETE. You should also understand rows, columns, data types, and NULL.
A primary key is a constraint that identifies each row in a table. It guarantees two things:
- Every primary-key value is unique.
- A primary-key column cannot contain
NULL.
A table has one primary key constraint. The constraint can contain one column or several columns.
Choosing a column for the key
A candidate key is a column, or group of columns, that could uniquely identify each row. For example, an email address might identify a customer, but it can change. A database-generated number usually has no business meaning and remains stable, so it is often a practical primary key.
| Key type | Example | Main consideration |
|---|---|---|
| Natural key | `email` or `country_code` plus `tax_number` | Has meaning outside the database, but may change |
| Surrogate key | `customer_id` | Has no business meaning, but is stable and compact |
Choose a key that is stable, always available, and as small as practical. Do not use a value as a primary key merely because it is currently unique. Future changes can break that assumption.
Defining a single-column primary key
You can declare the key beside the column:
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);PRIMARY KEY combines uniqueness and non-nullability. The separate UNIQUE constraint on email protects a different rule: two customers cannot use the same email address. A unique column is not automatically the table's primary key.
You can also define the constraint separately. This style makes the constraint name explicit:
CREATE TABLE products (
product_id INTEGER NOT NULL,
name VARCHAR(100) NOT NULL,
CONSTRAINT pk_products PRIMARY KEY (product_id)
);Naming constraints helps you refer to them later when changing a table.
Defining a composite primary key
A composite primary key uses multiple columns together. The combination must be unique, although each column can repeat by itself.
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)
);This design allows a product to appear in many orders and an order to contain many products. It prevents the same product from appearing twice in one order.
Exercise
Can a table have a primary key on email and a separate UNIQUE constraint on customer_id?
Show answer
Yes, but this is usually unnecessary if customer_id is already the stable identifier. The primary key should represent the table's main identity, while other candidate identifiers can use UNIQUE constraints.