# Foreign Keys & Relationships

> Link tables with a FOREIGN KEY so every order points at a real customer, and choose what happens on delete.

Subject: SQL | Lesson 5 of 44 | 7 min read
Interactive lesson: https://codewithanimation.in/sql/foreign-keys-and-relationships
Previous: [Primary Keys & Uniqueness](https://codewithanimation.in/sql/primary-keys-and-uniqueness.md) | Next: [SELECT & Column Labels](https://codewithanimation.in/sql/select-and-column-labels.md)

## A foreign key points at another table

A foreign key is a column whose values must match a row in another table. Here `orders.customer_id` must match a real `customers.id`. This guarantee is called referential integrity.

If you do not name the column in the other table, PostgreSQL uses its primary key. A `NULL` in the foreign key column is allowed and skips the check, unless you also add `NOT NULL`.

One customer with many orders is a one-to-many relationship. A many-to-many relationship, such as students and courses, needs a third table with a foreign key to each side.

## No orphan rows

Without a foreign key, an order could point at customer 99 who does not exist. Reports would break and nobody would know why.

With a foreign key, the database refuses the bad order for you, every time, from every program that writes to it.

## Declare the link and choose the delete rule

Add `REFERENCES` to the column. The optional `ON DELETE` part says what happens to orders when their customer is deleted:

```sql
CREATE TABLE orders (
  id integer PRIMARY KEY,
  customer_id integer
    REFERENCES customers (id)
    ON DELETE NO ACTION,
  item text
);
```

Inserting an order for customer 99 fails: `insert or update on table "orders" violates foreign key constraint`. The detail says the key is not present in table `customers`.

The delete rules: `NO ACTION` (the default) refuses to delete a customer who still has orders. `RESTRICT` does the same and cannot be postponed. `CASCADE` deletes the orders too. `SET NULL` keeps the orders and clears `customer_id`.

## Common mistake: CASCADE can delete more than you expect

`ON DELETE CASCADE` is convenient, and it can remove a lot of rows with one statement. Use it only for rows that cannot exist without their parent.

Also remember that a foreign key does not create an index on the referencing column. When you delete or update a customer, PostgreSQL must look through `orders`, so an index on `customer_id` is often worth adding.

## Tip: Pick the rule by asking one question

Can the child row exist alone? If not, use `CASCADE`. If it can exist and the link is optional, use `SET NULL`. If it is an independent thing that deserves protection, keep `NO ACTION` or `RESTRICT`.

## Try it: Break the link, then change the rule

Try an order for customer 99, then delete customer 1 under each `ON DELETE` rule and watch what happens to the orders.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/foreign-keys-and-relationships

## Check yourself

### Question 1

What does a foreign key guarantee?

- A. Every non-NULL value in the column matches a row in the referenced table
- B. Every value in the column is unique
- C. The referenced table can never lose a row

Correct answer: A

A foreign key keeps references honest: each non-NULL value must exist in the table it points at.

- Why not B: That is what UNIQUE does, not a foreign key.
- Why not C: A row can be deleted when nothing references it, or by CASCADE.

### Question 2

`orders.customer_id` has `ON DELETE CASCADE`. You delete customer 1, who has two orders. What happens?

- A. The two orders are deleted too
- B. The delete is refused
- C. The orders stay, with customer_id set to NULL

Correct answer: A

CASCADE passes the delete on to the rows that reference the deleted row.

- Why not B: That is what NO ACTION and RESTRICT do.
- Why not C: That is what SET NULL does.

### Question 3

Which design models students taking many courses, where each course has many students?

- A. A third table with a foreign key to students and one to courses
- B. One foreign key from students to courses
- C. A UNIQUE column in both tables

Correct answer: A

A many-to-many relationship is stored in a junction table that holds two foreign keys.

- Why not B: That gives each student at most one course.
- Why not C: UNIQUE does not link tables.

## Remember this

- A foreign key requires each non-NULL value to match a row in the table it references.
- NO ACTION and RESTRICT block deleting a referenced row, CASCADE deletes the children, and SET NULL clears the link.
- A many-to-many relationship needs a junction table with two foreign keys.
- PostgreSQL does not index a foreign key column for you, so add an index when you query or delete by it.
