Sub topic 1
Why Tables Need Keys
Prerequisites
This chapter assumes you can write basic SELECT, INSERT, UPDATE, and DELETE statements. It also assumes you can create a table with CREATE TABLE and pick column data types. Finally, you should know what rows, columns, and NULL mean. Examples use PostgreSQL syntax. Other databases differ in small ways, and later chapters cover those differences.
The problem: rows without identity
A relational table is a set of rows. SQL does not give a row a built-in name. If you want to change one row, you must describe it with a WHERE clause. That works only if the description matches exactly the row you mean.
Consider a table with no keys:
CREATE TABLE customers_loose (
name VARCHAR(100),
email VARCHAR(255)
);
INSERT INTO customers_loose (name, email) VALUES ('Ana Silva', '[email protected]');
INSERT INTO customers_loose (name, email) VALUES ('Ana Silva', '[email protected]');
INSERT INTO customers_loose (name, email) VALUES ('Ana Silva', NULL);The database accepts all three inserts. Now you have two identical rows and a third row that may or may not be the same person. Suppose you run this:
UPDATE customers_loose
SET email = '[email protected]'
WHERE name = 'Ana Silva';It changes all three rows. There is no way to update only one of them, because nothing tells them apart. A key fixes this by making every row addressable.
What a key is
A key is a column, or a combination of columns, whose values identify a row. A key makes two promises:
- Uniqueness: no two rows have the same key value.
- Presence: every row has a value for the key. For a primary key, that value cannot be
NULL.
When these promises hold, a statement such as WHERE customer_id = 42 matches at most one row. You can update, delete, and reference that row with confidence.
Two jobs: row identity and integrity
Keys do two separate jobs in a database.
- Row identity. A primary key names each row inside its own table. It prevents duplicate rows and gives every row a stable handle.
- Links between tables. A foreign key is a column in one table that stores the key value of a row in another table. The database checks that the value points to a row that exists. This rule is called referential integrity.
Without foreign keys, a link between tables is only a convention. Your application might write customer_id = 999 into an orders table even though no such customer exists. The database would store it without complaint. With a foreign key declared, the database rejects the insert.
What goes wrong without keys
These are the failures that keys prevent.
| Problem | Example | Constraint that prevents it |
|---|---|---|
| Duplicate rows | The same customer is inserted twice | Primary key or `UNIQUE` |
| Ambiguous updates | An `UPDATE` hits several rows by mistake | Primary key |
| Missing identity | A row has no identifying value | Primary key (implies `NOT NULL`) |
| Orphan rows | An order refers to a deleted customer | Foreign key |
| Dangling references | An order refers to a customer that never existed | Foreign key |
An orphan row is a child row whose parent no longer exists. Orphans cause quiet errors. A report that joins orders to customers with an inner join will drop orphaned orders, so totals come out wrong and nothing raises an error.
How the pieces fit together
Here is the model this tutorial builds. One table holds customers. Another holds orders. Each order stores the key of the customer who placed it.
The PK marks the primary key of each table. The FK marks the foreign key that points back to customers. The line between them reads "one customer places zero or more orders".
A first look at the fixed design
Here is the earlier problem solved with keys. This is the schema the next chapters explain piece by piece.
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
);Compare this with the loose table:
customer_idis generated by the database and is the primary key. Each customer has a unique, non-null handle.emailisUNIQUEandNOT NULL, so the same person cannot be entered twice with the same address.orders.customer_idisNOT NULLandREFERENCES customers, so every order must belong to an existing customer.
You can now test it:
INSERT INTO customers (email, name) VALUES ('[email protected]', 'Ana Silva');
-- Works: customer 1 exists
INSERT INTO orders (customer_id) VALUES (1);
-- Fails: a second customer with the same email
INSERT INTO customers (email, name) VALUES ('[email protected]', 'Another Ana');
-- Fails: no customer 999
INSERT INTO orders (customer_id) VALUES (999);The second and fourth statements fail with constraint violation errors. The database enforces the rules for every application, script, and manual query that touches the tables.
Why enforce this in the database
You could check these rules in application code. That is risky for three reasons.
- Several applications, scripts, and people may write to the same database. Each would need the same checks.
- Application checks race with each other. Two requests can both see that a customer exists, and one can delete it before the other inserts the order. A database constraint is checked as part of the write itself, so this race cannot leave an orphan.
- Bugs and one-off fixes happen. A constraint still holds when someone runs a quick manual
DELETE.
Application checks are still useful, because they give users friendly messages. Treat them as a convenience, and treat the database constraint as the guarantee.
Keys and the rest of this tutorial
The chapters that follow build on this one in order:
- Candidate keys, which are the columns that could identify a row.
- Primary keys, and the choice between natural and surrogate keys.
- Composite keys and generated values.
- Foreign keys, referential integrity, and
ON DELETEandON UPDATEactions. - One-to-many and many-to-many relationships, joins, and self-references.
- Indexing, changing constraints on existing tables, database differences, and common mistakes.
Keep the two jobs in mind as you read. The primary key identifies a row. The foreign key connects rows to one another.
Exercise
A table payments has the columns amount and paid_at, and no keys. Two payments of 20.00 are recorded at the same second. You run DELETE FROM payments WHERE amount = 20.00 AND paid_at = '2026-11-27 10:00:00'; to remove one of them. What happens, and how would a primary key help?
Show answer
The statement deletes both rows, because the WHERE clause matches both and nothing distinguishes them. With a primary key such as a generated payment_id, each payment has its own value, so DELETE FROM payments WHERE payment_id = 7; removes exactly one row. The key also stops accidental exact duplicates from being treated as the same row.
Exercise
An orders table has a customer_id column with no foreign key. Someone deletes customer 5, who has three orders. Name the kind of row that is now left in orders, and say what a foreign key declared on customer_id would have done at the time of the delete.
Show answer
The three orders are orphan rows, because they refer to a customer that no longer exists. With a foreign key on customer_id, the default behavior (NO ACTION) rejects the DELETE on the customer while orders still reference it. Chapters on referential actions show how to choose other behaviors, such as CASCADE.