FOREIGN KEY

Updated · 10 min read
mediumPostgreSQL 18sqlforeign-keyreferential-integritycascadeconstraintsinterview

A foreign key is a column whose values must match a key in another table, so a row can never point to something that doesn't exist. A payment's student_id says who paid. If that number were 104, and there's no student 104, the payment would belong to nobody, and every report that joins payments to students would quietly lose it. A foreign key makes the database refuse that payment. This lesson covers how foreign keys work in both directions, the Fee Tracker's own keys, and the ON DELETE actions that decide what happens to dependent rows.

In One Minute

  • REFERENCES other_table (column) makes a column a foreign key: every value must exist in that column.
  • It works both ways: no row may point to a missing parent, and a parent with dependents can't be deleted.
  • The referenced column must be a primary key or UNIQUE.
  • NULL in a foreign key is allowed: it points to nothing, on purpose.
  • ON DELETE CASCADE deletes dependents too; ON DELETE SET NULL clears their link; the default refuses.

The Basics

SQL
column_name data_type REFERENCES parent_table (parent_column)

Or as a table constraint, which you need when the key has several columns:

SQL
FOREIGN KEY (column_name, ...) REFERENCES parent_table (parent_column, ...)

The table holding the foreign key is the child (payments); the table it points to is the parent (students). The Fee Tracker's payments table has student_id INTEGER NOT NULL REFERENCES students (student_id), so a payment for a student who doesn't exist is refused:

SQL▶ Try it
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (104, 5, 225.00, '2026-01-05', '2026-01-05', 'card');
Output
ERROR:  insert or update on table "payments" violates foreign key constraint "payments_student_id_fkey"
DETAIL:  Key (student_id)=(104) is not present in table "students".

The detail line is the whole story: there's no 104 in students. This protection is called referential integrity: every reference leads somewhere real.

student_id 103 matches a student; 104 matches nothing and is refused

Protecting the Parent

A foreign key also stops you from removing a row that others depend on. Navika has an enrollment and two payments, so deleting her is refused:

SQL▶ Try it
DELETE FROM students WHERE student_id = 103;
Output
ERROR:  update or delete on table "students" violates foreign key constraint "enrollments_student_id_fkey" on table "enrollments"
DETAIL:  Key (student_id)=(103) is still referenced from table "enrollments".

Changing her id is refused for the same reason: UPDATE students SET student_id = 113 WHERE student_id = 103 would leave her enrollment pointing at 103, which would no longer exist. A parent row with no dependents can be deleted freely. Git Basics has no enrollments:

SQL▶ Try it
DELETE FROM courses WHERE course_id = 6
RETURNING title;
Output
   title
------------
 Git Basics
(1 row)

The Fee Tracker's Foreign Keys

Every connection in the Fee Tracker is a foreign key. The ones pointing at students:

SQL▶ Try it
SELECT tc.table_name, kcu.column_name, ccu.table_name AS references_table
FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
  ON kcu.constraint_name = tc.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
  ON ccu.constraint_name = tc.constraint_name
WHERE tc.constraint_type = 'FOREIGN KEY'
  AND ccu.table_name = 'students'
ORDER BY tc.table_name, kcu.column_name;
Output
 table_name  | column_name | references_table
-------------+-------------+------------------
 enrollments | student_id  | students
 payments    | student_id  | students
 students    | mentor_id   | students
(3 rows)

(The JOINs are explained in How Joins Work; for now, read the result.) Three keys point at students. The third is a table pointing at itself: mentor_id must be another student's id, which is how Srihitha mentors Advitha. A few more keys you've met without knowing:

  • courses.prerequisite_id points at courses, so Java OOP's prerequisite must be a real course.
  • students (city, state) points at cities, a two-column foreign key: a student in Austin, TX is refused until Austin is in cities.
  • payments (student_id, course_id) points at enrollments, so you can only pay for a course you're enrolled in.

That last one is a composite foreign key, and it catches a subtle mistake. Advitha (102) exists and JavaScript Basics (5) exists, but she isn't enrolled in it:

SQL▶ Try it
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 5, 225.00, '2026-01-05', '2026-01-05', 'card');
Output
ERROR:  insert or update on table "payments" violates foreign key constraint "payments_student_id_course_id_fkey"
DETAIL:  Key (student_id, course_id)=(102, 5) is not present in table "enrollments".
payments points at students, courses and enrollments; students points at itself and at cities

Writing Your Own

The referenced column must be a primary key or have a UNIQUE constraint, so each value matches exactly one parent row. Pointing at students (first_name) fails with there is no unique constraint matching given keys for referenced table "students". A foreign key column may be NULL, which means "points to nothing", unless you also make it NOT NULL:

SQL▶ Try it
CREATE TABLE study_sessions (
  session_id INTEGER PRIMARY KEY,
  student_id INTEGER NOT NULL REFERENCES students (student_id),
  course_id  INTEGER REFERENCES courses (course_id),
  minutes    INTEGER NOT NULL
);
 
INSERT INTO study_sessions VALUES
  (1, 103, 5, 45),
  (2, 101, 6, 60),
  (3, 101, NULL, 30);
 
SELECT * FROM study_sessions ORDER BY session_id;
Output
CREATE TABLE
 
INSERT 0 3
 
 session_id | student_id | course_id | minutes
------------+------------+-----------+---------
          1 |        103 |         5 |      45
          2 |        101 |         6 |      60
          3 |        101 |      NULL |      30
(3 rows)

Session 3 isn't for any course (Srihitha was reviewing on her own), so its course_id is NULL, which the foreign key allows. Every session must have a student, though, so student_id is NOT NULL as well.

ON DELETE: What Happens to the Children

ON DELETE decides what happens to child rows when their parent is deleted. Srihitha has two Git Basics (course 6) study sessions. Here's what deleting Git Basics does under each setting:

SettingDeleting course 6 does this
(none) or NO ACTIONRefused while sessions point to it
RESTRICTRefused, checked immediately
CASCADEDeletes the two sessions too
SET NULLKeeps the sessions, with course_id set to NULL

With ON DELETE CASCADE:

SQL▶ Try it
CREATE TABLE study_sessions (
  session_id INTEGER PRIMARY KEY,
  student_id INTEGER NOT NULL REFERENCES students (student_id),
  course_id  INTEGER REFERENCES courses (course_id) ON DELETE CASCADE,
  minutes    INTEGER NOT NULL
);
 
INSERT INTO study_sessions VALUES (1, 103, 5, 45), (2, 101, 6, 60), (3, 101, 6, 30);
 
DELETE FROM courses WHERE course_id = 6;
 
SELECT * FROM study_sessions ORDER BY session_id;
Output
CREATE TABLE
 
INSERT 0 3
 
DELETE 1
 
 session_id | student_id | course_id | minutes
------------+------------+-----------+---------
          1 |        103 |         5 |      45
(1 row)

Both Git Basics sessions vanished with the course. With ON DELETE SET NULL, they stay, unlinked:

SQL▶ Try it
CREATE TABLE study_sessions (
  session_id INTEGER PRIMARY KEY,
  student_id INTEGER NOT NULL REFERENCES students (student_id),
  course_id  INTEGER REFERENCES courses (course_id) ON DELETE SET NULL,
  minutes    INTEGER NOT NULL
);
 
INSERT INTO study_sessions VALUES (1, 103, 5, 45), (2, 101, 6, 60), (3, 101, 6, 30);
 
DELETE FROM courses WHERE course_id = 6;
 
SELECT * FROM study_sessions ORDER BY session_id;
Output
CREATE TABLE
 
INSERT 0 3
 
DELETE 1
 
 session_id | student_id | course_id | minutes
------------+------------+-----------+---------
          1 |        103 |         5 |      45
          2 |        101 |      NULL |      60
          3 |        101 |      NULL |      30
(3 rows)

The study time is kept, and only the link is cleared. ON UPDATE CASCADE works the same way for changed keys: renumbering a parent renumbers its children. NO ACTION and RESTRICT differ only in timing, which matters with deferred constraints, an advanced topic.

Deleting course 6: refused by default, its sessions deleted with CASCADE, unlinked with SET NULL

Common Mistakes

Forgetting the foreign key. Without it, orphans such as a payment for student 104 slip in unnoticed.

Deleting parents first. Delete or move the children first, or the delete is refused.

Pointing at a column that isn't unique. A foreign key needs a primary key or UNIQUE column to point at.

Cascading deletes on important data. Deleting a student with CASCADE on payments would erase their payment history.

Interview Corner

What is a foreign key?

A column, or set of columns, whose values must match a primary key or unique key in another table (or the same table). It enforces referential integrity: no row can point to something that doesn't exist.

What does ON DELETE CASCADE do?

When a parent row is deleted, the child rows that reference it are deleted automatically, and the cascade continues to their children.

Can a foreign key column be NULL?

Yes, unless it's also NOT NULL. A NULL foreign key points to nothing and isn't checked.

Practice

Challenge (module checkpoint): Try to record a $100.00 card payment for student 105 in JavaScript Basics (course 5), due and paid on 2026-01-05. Run it and read the error: which constraint failed, and why?

Show solution
SQL▶ Try it
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (105, 5, 100.00, '2026-01-05', '2026-01-05', 'card');
Output
ERROR:  insert or update on table "payments" violates foreign key constraint "payments_student_id_fkey"
DETAIL:  Key (student_id)=(105) is not present in table "students".

payments_student_id_fkey refused the row because there's no student 105 in students. The payment would have belonged to nobody. To record it, the student must be added to students and enrolled in the course first, because the composite key to enrollments checks that too.

Quick check: FOREIGN KEY

3 questions
1Navika (103) has payments. What does DELETE FROM students WHERE student_id = 103; do?
2What must the referenced column be?
3course_id has ON DELETE SET NULL. Course 6 is deleted. What happens to its study sessions?

Key Takeaways

You want toWrite
Link to a parentstudent_id INTEGER REFERENCES students (student_id)
A two-column linkFOREIGN KEY (student_id, course_id) REFERENCES enrollments (student_id, course_id)
Delete children with the parent... REFERENCES courses (course_id) ON DELETE CASCADE
Keep children, clear the link... ON DELETE SET NULL

Was this tutorial helpful?

Lesson 33 of 115