Foreign keys link a column to the primary key of another table. Use ON DELETE CASCADE to auto-delete related rows. Foreign keys prevent orphaned data and enforce referential integrity at the database level.
Foreign Keys
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
total NUMERIC(10,2)
);
ON DELETE options
- CASCADE — delete related rows
- SET NULL — set FK to NULL
- RESTRICT — block deletion