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
REFERENCESnames the parent table and column.ON DELETE CASCADEremoves the children with the parent.UNIQUEon a pair of columns forbids duplicate rows.
Keywords and builtins used here
CASCADECHECKCREATEDELETEINTEGERNOTNULLONREFERENCESTABLETEXTUNIQUE
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.
Step 2 of 8 in Tables & rows, step 15 of 23 in Language basics.