typestar

Foreign keys in SQL

A foreign key ties a child row to the parent it belongs to.

CREATE TABLE order_items (
    order_id INTEGER NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
    sku TEXT NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    UNIQUE (order_id, sku)
);

How it works

  1. REFERENCES names the parent table and column.
  2. ON DELETE CASCADE removes the children with the parent.
  3. UNIQUE on a pair of columns forbids duplicate rows.

Keywords and builtins used here

The run, in numbers

Lines
6
Characters to type
186
Tokens
41
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 31 seconds.

Type this snippet

Step 2 of 8 in Tables & rows, step 15 of 23 in Language basics.

← Previous Next →