Foreign Key

A foreign key is a column (or a set of columns) in one table that establishes a relationship with the primary key of another table, ensuring referential integrity between the two tables.

A foreign key is used to enforce relationships between tables, ensuring that values in the foreign key column match values in the primary key column of the referenced table. This prevents orphan records (records without valid references).

For example, if we have a Students table and a Courses table, we can create an Enrollments table that links students to courses using foreign keys.

A foreign key can enforce cascading actions such as:

  • ON DELETE CASCADE: Deletes related records when the referenced record is deleted.
  • ON UPDATE CASCADE: Updates foreign key values when the primary key is updated.

Example SQL Query (Defining a Foreign Key):

CREATE TABLE Students (
student_id INT PRIMARY KEY,
name VARCHAR(100),
age INT
);
CREATE TABLE Enrollments (
enrollment_id INT PRIMARY KEY,
student_id INT,
course_name VARCHAR(50),
FOREIGN KEY (student_id) REFERENCES Students(student_id) ON DELETE CASCADE
);

Here, Enrollments.student_id references Students.student_id, ensuring that a student must exist in the Students table before they can be enrolled.

If a student is deleted from the Students table, all their enrollments will be automatically deleted due to ON DELETE CASCADE.