Sub topic 2
Linking Tables with a Foreign Key
This chapter assumes you can write SELECT, INSERT, UPDATE, and DELETE, create tables with CREATE TABLE, and know that a primary key uniquely identifies each row. Examples use PostgreSQL syntax.
Linking tables with a foreign key
A foreign key is a column in one table whose values must match a primary key value in another table. The column in the child table refers to the parent table through a REFERENCES clause.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
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
);What referential integrity rejects
Referential integrity means every foreign key value points to an existing parent row. The database rejects these statements:
-- Fails: no customer with customer_id 999 exists
INSERT INTO orders (customer_id) VALUES (999);
-- Fails while any order still references customer 1
DELETE FROM customers WHERE customer_id = 1;Choosing ON DELETE and ON UPDATE behavior
A referential action tells the database what to do with child rows when a parent row changes. The default, NO ACTION, rejects the change. Other options:
| Action | Effect on child rows |
|---|---|
| NO ACTION | Rejects the parent change if children exist |
| RESTRICT | Rejects the parent change immediately |
| CASCADE | Applies the change to child rows too |
| SET NULL | Sets the foreign key to NULL (the column must allow NULL) |
For example, REFERENCES customers (customer_id) ON DELETE CASCADE deletes a customer's orders along with the customer.
Modeling one-to-many relationships
In a one-to-many relationship, one parent row has many child rows. The many side holds the foreign key. One customer places many orders, so orders holds customer_id.
Many-to-many relationships with junction tables
An order can contain many products, and a product can appear in many orders. Model this with a junction table that holds one foreign key to each side.
CREATE TABLE products (
product_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (order_id) ON DELETE CASCADE,
product_id INTEGER NOT NULL REFERENCES products (product_id) ON DELETE RESTRICT,
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id)
);Exercise
Using the tables above, what happens if you run DELETE FROM orders WHERE orderid = 5 while orderitems has rows for order 5?
Show answer
The rows in orderitems for order 5 are deleted too, because orderitems.order_id uses ON DELETE CASCADE.