Skip to content
Justice Tech School

Foreign Keys

A foreign key links a column to a primary key in another table and keeps data consistent.

Example
CREATE TABLE notes (id INTEGER PRIMARY KEY, student_id INTEGER REFERENCES students(id), text TEXT);
INSERT INTO notes (student_id, text) VALUES (1, 'great');
SELECT s.name, n.text FROM notes n JOIN students s ON s.id = n.student_id;

Result

name | text
Ada  | great

Exercise

Link to another table.

student_id INT  students(id)

Quiz Test

What does a foreign key protect?

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