How foreign keys work
Reference another row
A foreign key value points to a candidate key—usually the primary key—of another table.
CREATE TABLE enrollments (
student_id INTEGER NOT NULL,
course_id INTEGER NOT NULL,
FOREIGN KEY (student_id) REFERENCES students(id),
FOREIGN KEY (course_id) REFERENCES courses(id)
);
Protect integrity
The constraint prevents references to rows that do not exist and can define what happens when a referenced row changes or is deleted.
Choose delete behavior
RESTRICTorNO ACTIONrejects unsafe deletionCASCADEremoves dependent rowsSET NULLclears an optional reference- Choose deliberately; cascading deletion can remove much data
Enable SQLite checks
SQLite applications should enable enforcement for each connection with PRAGMA foreign_keys = ON;. PostgreSQL and MySQL enforce supported foreign keys by default.
PRAGMA foreign_keys = ON;