Sub topic 1
Why Tables Need Keys
Prerequisites
You should know how to create tables and use basic SELECT, INSERT, UPDATE, and DELETE statements. You should also understand rows, columns, data types, and NULL.
A database table stores facts as rows. A key gives those rows a reliable identity and describes how rows in different tables are related. Without keys, applications may not know which row to update, and related data can become inconsistent.
A row needs a stable identity
Suppose a customers table contains two people named Sam Lee. A name cannot identify one specific row. An email address might identify a customer, but email addresses can change or may be entered incorrectly.
A candidate key is a column, or group of columns, that could uniquely identify each row. A table can have several candidate keys. The database design chooses one of them as the primary key.
A primary key guarantees that:
- Every row has a value for the key.
- No two rows have the same key value.
- Other tables can refer to the row using that value.
These guarantees come from NOT NULL and UNIQUE behavior built into the primary key constraint.
| Key type | Example | Typical use |
|---|---|---|
| Natural key | `email` | A meaningful value already present in the data |
| Surrogate key | `customer_id` | A generated identifier with no business meaning |
| Composite key | `(order_id, product_id)` | A unique combination of multiple columns |
Keys protect relationships
A foreign key is a column that refers to a primary key, or another unique key, in a related table. It expresses a rule such as “every order belongs to an existing customer.”
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
ordered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);The orders.customer_id foreign key prevents an order from pointing to a customer that does not exist. This protection is called referential integrity. It also gives queries a dependable path for joining orders to customers.
Choose keys deliberately
Use a natural key when the value is stable, truly unique, and unlikely to change. Use a surrogate key when the business value can change, is lengthy, or has uncertain uniqueness. Keep a separate UNIQUE constraint for important natural identifiers such as email addresses.
A primary key does not automatically model every business rule. You may still need checks, unique constraints, and appropriate data types. A key should identify a row, not carry unrelated business meaning.
Exercise
Why is a customer's name usually a poor primary key?
Show answer
Names are not guaranteed to be unique and can change, so they cannot provide a stable identity for one row.