Lesson 34 of 60 – FOREIGN KEY
57%

FOREIGN KEY in SQL

A FOREIGN KEY is a constraint used to create a relationship between two tables. It connects a column in one table with a primary key or suitable unique key in another table.

Note: A FOREIGN KEY helps maintain referential integrity by ensuring that related values follow the rules defined between tables.

1. What is a FOREIGN KEY?

A FOREIGN KEY is a column or group of columns that references a key in another table.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
);

Here, course_id in the students table references course_id in the courses table.

2. Why is FOREIGN KEY Important?

A foreign key helps maintain valid relationships between related tables.

  • Connects related tables
  • Maintains referential integrity
  • Helps prevent invalid references
  • Represents relationships between data
  • Supports relational database design

3. FOREIGN KEY Syntax

The basic table-level syntax is:

FOREIGN KEY (column_name)
REFERENCES parent_table(parent_column)

Example:

FOREIGN KEY (course_id)
REFERENCES courses(course_id)

4. Parent Table and Child Table

The table containing the referenced key is commonly called the parent table.

The table containing the foreign key is commonly called the child table.

courses
--------
course_id
course_name

students
--------
student_id
course_id

Here, courses is the parent table and students is the child table.

5. Create a Parent Table

First, create the table that contains the referenced key.

CREATE TABLE courses (
    course_id INT PRIMARY KEY,
    course_name VARCHAR(100) NOT NULL
);

The course_id is the primary key of the courses table.

6. Create a Child Table

Now create a table that references the parent table.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100),
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
);

The students table references the courses table.

7. FOREIGN KEY During CREATE TABLE

A foreign key can be defined while creating a table.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100),
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
);

This creates the relationship immediately.

8. Insert a Valid FOREIGN KEY Value

The referenced value should exist in the parent table when the foreign key requires a matching parent.

INSERT INTO courses (course_id, course_name)
VALUES (1, 'Python');

INSERT INTO students (student_id, name, course_id)
VALUES (101, 'Rahul', 1);

Because course_id 1 exists in courses, the student can reference that course.

9. Invalid FOREIGN KEY Value

If a student references a course ID that does not exist, the database may reject the insert.

INSERT INTO students (student_id, name, course_id)
VALUES (102, 'Amit', 99);

If course_id 99 does not exist in courses, the foreign key constraint can prevent the operation.

10. FOREIGN KEY with SELECT

Foreign key columns are often used when joining related tables.

SELECT students.name, courses.course_name
FROM students
INNER JOIN courses
ON students.course_id = courses.course_id;

This displays student names with their course names.

11. Named FOREIGN KEY Constraint

You can give a foreign key constraint a specific name.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    course_id INT,
    CONSTRAINT fk_student_course
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
);

The foreign key constraint is named fk_student_course.

12. Add FOREIGN KEY with ALTER TABLE

You can add a foreign key to an existing table.

ALTER TABLE students
ADD CONSTRAINT fk_student_course
FOREIGN KEY (course_id)
REFERENCES courses(course_id);

The relationship is added after the table has already been created.

13. FOREIGN KEY with Multiple Tables

A database can contain many related tables.

students
courses
teachers
departments

Foreign keys can be used to connect these tables according to the database design.

14. FOREIGN KEY with a Composite Key

A foreign key can contain multiple columns when it references a composite key.

CREATE TABLE enrollments (
    student_id INT,
    course_id INT,
    PRIMARY KEY (student_id, course_id)
);

A related table can reference the appropriate combination of columns.

15. Composite FOREIGN KEY

A composite foreign key contains more than one column.

FOREIGN KEY (student_id, course_id)
REFERENCES enrollments(student_id, course_id)

The number and order of referenced columns must correspond to the referenced key.

16. FOREIGN KEY and NULL

A foreign key column can generally contain NULL when the column allows NULL and no other constraint prevents it.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
);

A NULL course_id can represent a student who currently has no course assigned, depending on the application design.

17. FOREIGN KEY with NOT NULL

You can combine FOREIGN KEY with NOT NULL when every child record must have a related parent.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    course_id INT NOT NULL,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
);

Now course_id cannot be NULL.

18. ON DELETE CASCADE

ON DELETE CASCADE can automatically delete related child records when the referenced parent record is deleted.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
    ON DELETE CASCADE
);

Deleting a referenced course can then delete its related student records according to this rule.

19. ON UPDATE CASCADE

ON UPDATE CASCADE can automatically update matching foreign key values when the referenced key changes.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
    ON UPDATE CASCADE
);

This keeps related key values synchronized according to the constraint.

20. ON DELETE SET NULL

ON DELETE SET NULL can set the foreign key value to NULL when the referenced parent record is deleted.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
    ON DELETE SET NULL
);

The course_id column must allow NULL for this behavior.

21. ON DELETE RESTRICT

ON DELETE RESTRICT can prevent deletion of a parent record when related child records exist.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
    ON DELETE RESTRICT
);

The exact default behavior can vary by database system.

22. Drop a FOREIGN KEY

You can remove a foreign key constraint using ALTER TABLE.

ALTER TABLE students
DROP FOREIGN KEY fk_student_course;

In MySQL, the named foreign key constraint is removed.

23. FOREIGN KEY and DELETE

Deleting a parent record can be restricted when child records reference it.

DELETE FROM courses
WHERE course_id = 1;

If students still reference course_id 1, the database may reject the deletion unless an appropriate ON DELETE action is configured.

24. FOREIGN KEY and UPDATE

Updating a referenced key can also be affected by foreign key rules.

UPDATE courses
SET course_id = 10
WHERE course_id = 1;

The operation may be restricted or cascaded depending on the foreign key configuration.

25. PRIMARY KEY vs FOREIGN KEY

PRIMARY KEY and FOREIGN KEY have different purposes.

  • PRIMARY KEY uniquely identifies records in its own table.
  • FOREIGN KEY references a key in another table.
  • A table can have one primary key constraint.
  • A table can have multiple foreign key constraints.

26. Common FOREIGN KEY Mistake

A common mistake is trying to create a foreign key when the referenced column does not have a suitable key or the column definitions are incompatible.

FOREIGN KEY (course_id)
REFERENCES courses(course_id)

Before creating the relationship, check that the referenced column is appropriately indexed or keyed and that the column definitions are compatible.

Tip: Always check both table structures before creating a FOREIGN KEY.

27. Check FOREIGN KEY Definition

In MySQL, you can inspect the table definition using SHOW CREATE TABLE.

SHOW CREATE TABLE students;

This can help you check foreign key definitions and other constraints.

28. Practical FOREIGN KEY Example

Suppose an academy has courses and students.

CREATE TABLE courses (
    course_id INT PRIMARY KEY AUTO_INCREMENT,
    course_name VARCHAR(100) NOT NULL
);

CREATE TABLE students (
    student_id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
);

The course_id in students connects each student with a course.

29. FOREIGN KEY in a Real Project

In a student management system, a student can be connected to a course using a foreign key.

INSERT INTO courses (course_name)
VALUES ('Python Full Stack');

INSERT INTO students (name, course_id)
VALUES ('Rahul', 1);

The student references the course whose course_id is 1.

30. Complete FOREIGN KEY Example

Here is a complete example using PRIMARY KEY and FOREIGN KEY together.

CREATE TABLE courses (
    course_id INT PRIMARY KEY AUTO_INCREMENT,
    course_name VARCHAR(100) NOT NULL
);

CREATE TABLE students (
    student_id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE,
    course_id INT,
    FOREIGN KEY (course_id)
    REFERENCES courses(course_id)
    ON UPDATE CASCADE
    ON DELETE SET NULL
);

INSERT INTO courses (course_name)
VALUES ('Python'), ('SQL');

INSERT INTO students (name, email, course_id)
VALUES ('Rahul', 'rahul@example.com', 1);

Here, courses is the parent table and students is the child table. The course_id column creates the relationship between them.

📌 Key Points

  • FOREIGN KEY creates a relationship between tables.
  • It commonly references a PRIMARY KEY or suitable UNIQUE key in another table.
  • The referenced table is commonly called the parent table.
  • The table containing the foreign key is commonly called the child table.
  • FOREIGN KEY helps maintain referential integrity.
  • A foreign key can contain NULL when the column allows it.
  • ON DELETE CASCADE can remove related child records automatically.
  • ON DELETE SET NULL can set the foreign key to NULL.
  • ON UPDATE CASCADE can update related key values.
  • FOREIGN KEY constraints can be added or removed using ALTER TABLE.

🧠 Quick Quiz

Question: What is the main purpose of a FOREIGN KEY?