Understanding Foreign Key in SQL: Easy Tutorial for Students and Beginners

A Foreign Key is a column in one table that is used to connect it with another table.

Think of it like a relationship:

  • Your Aadhar Number is your primary key (your identity).
  • If your school database wants to link your exam records to you, they will store your Aadhar Number there as a foreign key.

So:

  • Primary Key = unique identity in its own table.
  • Foreign Key = reference to that identity in another table.

Rules of Foreign Key

  1. A foreign key in one table refers to the primary key in another table.
  2. It creates a relationship between two tables.
  3. Helps maintain data consistency (you can’t enter a value in foreign key if it doesn’t exist in the parent table).

Example in MySQL

Table 1: students

sql

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(50)
);

Data:

student_idname
1Ramesh
2Priya

Table 2: marks

sql

CREATE TABLE marks (
    mark_id INT PRIMARY KEY,
    student_id INT,
    subject VARCHAR(30),
    marks INT,
    FOREIGN KEY (student_id) REFERENCES students(student_id)
);

Here:

  • students.student_id = Primary Key
  • marks.student_id = Foreign Key (refers to students.student_id)

Insert Data

sql

INSERT INTO marks VALUES (1, 1, 'Maths', 90); -- ✅ Works (Ramesh exists)
INSERT INTO marks VALUES (2, 2, 'Science', 80); -- ✅ Works (Priya exists)
INSERT INTO marks VALUES (3, 5, 'English', 85); -- ❌ Error (No student with id 5)

The foreign key makes sure you can’t insert marks for a student who doesn’t exist in the students table.

Real-Life Analogy

  • Primary Key = Your Aadhar Number (your unique identity).
  • Foreign Key = When your bank account stores your Aadhar Number to link the account with you.

So foreign key is like a reference to another table’s primary key.

Super Simple Memory Trick

Just remember:
Foreign Key = Reference / Link

  • Lives in another table.
  • Points to the primary key in parent table.
  • Ensures data consistency.