Skip to content
Justice Tech School

FOREIGN KEY

A foreign key is a column that points to the primary key of another table. The database refuses values that do not exist there, which keeps your data consistent. ON DELETE CASCADE removes the child rows when the parent is deleted. SQLite needs PRAGMA foreign_keys = ON to enforce this.

Example
PRAGMA foreign_keys = ON;
CREATE TABLE reviews (
  id INTEGER PRIMARY KEY,
  course_id INTEGER NOT NULL,
  stars INTEGER,
  FOREIGN KEY (course_id) REFERENCES courses(id)
);
INSERT INTO reviews (course_id, stars) VALUES (4, 5);
SELECT reviews.stars, courses.title FROM reviews JOIN courses ON courses.id = reviews.course_id;

Result

stars | title
5     | Python

Exercise

Point the column at another table.

FOREIGN KEY (course_id)  courses(id)

Quiz Test

What does a foreign key guarantee?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.