Skip to the workspace
Pebellslearn by building
Data Constraints  ›  Lesson

Foreign Key

Foreign Key 15 minA foreign key makes a column accept only values that exist in a referenced key of another table, and ON DELETE rules decide what happens to children when a parent row is removed.

sql / Foreign Key

Explore each scene at your own pace.

01 · The rule

The rule

Foreign Key

A foreign key makes a column accept only values that exist in a referenced key of another table, and ON DELETE rules decide what happens to children when a parent row is removed.

Follow a reference to its parent key and test the chosen deletion policy.

Someone inserts an order for customer_id 99. There is no customer 99. The order ships, the invoice goes to nobody, and a report of "orders by city" quietly drops a row. A foreign key would have refused that insert on the spot.

The rule

A foreign key only accepts values that exist in the table it points to.

CREATE TABLE orders (
    order_id    INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL,
    product_id  INTEGER NOT NULL,
    quantity    INTEGER NOT NULL,
    FOREIGN KEY (customer_id) REFERENCES customers (customer_id),
    FOREIGN KEY (product_id)  REFERENCES products (product_id)
);

orders.customer_id is the child column; customers.customer_id is the parent it references, and it must be a primary key or have a UNIQUE constraint. The database now guards the link from both ends:

  • From the child side: inserting or updating an order with a customer_id that is not in customers is rejected.
  • From the parent side: deleting (or changing the id of) a customer who still has orders would leave orphans, so by default that is rejected too.

A NULL in the child column is allowed unless you also say NOT NULL — it means "not linked to anyone yet".

You choose what happens when a parent row is deleted with an ON DELETE rule:

Rule When the customer is deleted, their orders…
(default) / RESTRICT / NO ACTION block the delete
CASCADE are deleted too
SET NULL stay, with customer_id set to NULL
FOREIGN KEY (customer_id) REFERENCES customers (customer_id) ON DELETE CASCADE

(RESTRICT and NO ACTION differ only in the timing of the check, which rarely matters at this level.)

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.