Sub topic 1
Why Tables Need Keys
Prerequisites
This chapter assumes you can write basic SQL (SELECT, INSERT, UPDATE, DELETE), create tables with CREATE TABLE and column types, and understand rows, columns, and NULL.
Why tables need keys
A table is a set of rows. Without a way to tell rows apart, you cannot reliably update or delete one specific row. Two customers can share a name, so a key is a column or set of columns whose values identify exactly one row.
Keys also let the database reject duplicate or incomplete identities before they are stored.
Candidate keys: what can identify a row
A candidate key is a minimal set of columns whose values are unique across all rows. A table can have several candidate keys. A customer table might have both email and a national ID number. You choose one candidate as the primary key and treat the others as alternate keys.
Defining a primary key
A primary key is a constraint that combines UNIQUE and NOT NULL. Each table should have one.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
INSERT INTO customers (customer_id, email, name) VALUES (1, '[email protected]', 'Ana');
-- Fails: duplicate key value violates the primary key
INSERT INTO customers (customer_id, email, name) VALUES (1, '[email protected]', 'Ben');Natural versus surrogate keys
A natural key uses real-world data, such as an email address. A surrogate key is a generated value with no business meaning, such as customer_id. Natural keys can change, because people change email addresses, and changing a key means updating every table that references it. Surrogate keys stay stable. Use a natural key only when the value is truly permanent.
Generating key values
An identity column lets the database generate the key for you:
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ordered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO orders DEFAULT VALUES;The syntax differs by database:
| Database | Generated key syntax |
|---|---|
| PostgreSQL | GENERATED ALWAYS AS IDENTITY |
| MySQL | AUTO_INCREMENT |
| SQL Server | IDENTITY(1,1) |
Composite primary keys
When no single column is unique, combine several columns into one primary key. This junction table allows each product to appear once per order:
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)
);Exercise
A table records which students are enrolled in which courses. A student takes each course at most once. What primary key should the table use?
Show answer
A composite primary key of (studentid, courseid). Neither column is unique alone, but the pair is unique.