Sub topic 7
Linking tables with a foreign key
A foreign key is a constraint that ties the values in one column (or group of columns) to the values of a key in another table. This chapter covers how to declare one, what it can reference, and the errors you hit while setting one up. It assumes you can write CREATE TABLE statements, pick column data types, and understand NULL. It also assumes you have met primary keys in the earlier chapters. Examples use PostgreSQL syntax.
What a foreign key does
Storing a customer's details in every order row would duplicate data. Instead, orders stores only the customer's key, and the database keeps that value honest. The table holding the foreign key is the child table. The table it points to is the parent table.
The constraint adds one rule: every non-null value in the child's foreign key column must exist in the parent's referenced column. The next chapter covers what the database rejects and when. Here the focus is on declaring the link correctly.
Declaring a foreign key
The parent table must exist first. This pair of tables is the running example:
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 REFERENCES customers (customer_id) clause on the customer_id column is the foreign key. Three details matter:
REFERENCESnames the parent table and, in parentheses, the parent column.- The
NOT NULLis separate from the foreign key. The constraint alone allowsNULL, so you addNOT NULLwhen every order must have a customer. - If you omit the parent column list, the parent's primary key is used. Writing the column explicitly is clearer and survives later schema changes.
Column form and table form
The column form above works for single-column keys. The table form lists the constraint after the columns. It is required for composite keys and lets you give the constraint a name:
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL,
ordered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);The two definitions behave identically. Without CONSTRAINT name, PostgreSQL generates a name such as orders_customer_id_fkey. That generated name appears in error messages, so a deliberate name like fk_orders_customer makes failures easier to read and constraints easier to drop later.
What a foreign key can reference
A foreign key must point at columns that are guaranteed unique in the parent. That means a primary key or a UNIQUE constraint. It does not have to be the primary key:
CREATE TABLE newsletter_signups (
signup_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL REFERENCES customers (email)
);This works because customers.email is unique. Referencing the surrogate primary key is still the usual choice. It is short, it never changes, and it keeps the child table small. Referencing an email would force you to update every child row when a customer changes address.
Composite foreign keys
If the parent's key has several columns, the foreign key must list the same number of columns, in matching order:
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
product_id INTEGER NOT NULL,
PRIMARY KEY (order_id, product_id)
);
CREATE TABLE item_returns (
return_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
reason VARCHAR(200),
FOREIGN KEY (order_id, product_id)
REFERENCES order_items (order_id, product_id)
);The pair (order_id, product_id) must exist as a pair in order_items. Each column is not checked separately. Columns are matched by position, not by name, so the child's columns can have different names from the parent's.
Rules for matching columns
| Requirement | Detail |
|---|---|
| Compatible types | The child and parent columns must have comparable types. `INTEGER` to `INTEGER` is fine. `INTEGER` to `VARCHAR` is rejected. |
| Unique target | The referenced columns need a primary key or unique constraint covering exactly those columns. |
| Existing parent | The parent table must exist when the constraint is created. A table may reference itself. |
| Same column count | The lists on both sides must have the same length. |
Matching sizes is good practice even where the database allows a mismatch. A BIGINT primary key referenced by an INTEGER column compiles in PostgreSQL, but the child column overflows once key values pass about 2.1 billion.
Inspecting existing foreign keys
To see which foreign keys a table has, query the standard catalog or use \d orders in psql:
SELECT constraint_name, table_name
FROM information_schema.table_constraints
WHERE constraint_type = 'FOREIGN KEY'
AND table_name = 'orders';Errors you will meet while declaring keys
there is no unique constraint matching given keys for referenced table "customers": the referenced column is not a primary key or unique. Add aUNIQUEconstraint to the parent, or reference a different column.Key columns "customer_id" and "id" are of incompatible types: the two columns have types that cannot be compared. Change the child column to match the parent.violates foreign key constraint "fk_orders_customer"when adding the constraint to a populated table: existing child rows already contain values with no parent. Find them with aLEFT JOINwhere the parent key isNULL, then fix or delete them.
Exercise
Exercise
A shipments table must record which order each shipment belongs to, and every shipment must have an order. Write the CREATE TABLE statement, naming the foreign key constraint fk_shipments_order. Use the orders table from this chapter. What happens if you run it before orders exists?
Show answer
CREATE TABLE shipments (
shipmentid INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
orderid INTEGER NOT NULL,
shippedat TIMESTAMP,
CONSTRAINT fkshipmentsorder
FOREIGN KEY (orderid) REFERENCES orders (orderid)
);
The NOT NULL on orderid makes the link mandatory, because the foreign key alone would allow NULL. If orders does not exist yet, PostgreSQL fails with relation "orders" does not exist, so the parent table must be created first.