🔑 Understanding Primary & Foreign Keys in SQL – Your Database’s VIP Pass & Guest Pass
Imagine you’re running an exclusive club.
Let’s dive into this in the easiest way possible.
1️⃣ What is a Primary Key?
A Primary Key is a column (or a set of columns) in a table that uniquely identifies each row.
Example: In a Students table:
Here, StudentID is the Primary Key because it’s unique for every student.
2️⃣ What is a Foreign Key?
A Foreign Key is a column in one table that links to the Primary Key in another table.
Example: In a Courses table:
Here, StudentID is the Foreign Key that connects Courses to Students.
3️⃣ Difference Between Primary Key & Foreign Key
4️⃣ Relation Between Them
Think of them as Parent and Child.
Without the parent, the child’s record can’t exist in a meaningful way.
5️⃣ How to Use Them in SQL
Let’s create both keys in SQL.
-- Creating the Students table with a PRIMARY KEY
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Recommended by LinkedIn
Name VARCHAR(50),
Age INT
);
-- Creating the Courses table with a FOREIGN KEY
CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(50),
StudentID INT,
FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);
6️⃣ Example in Action
-- Inserting Students
INSERT INTO Students (StudentID, Name, Age) VALUES
(1, 'John', 20),
(2, 'Emma', 21);
-- Inserting Courses
INSERT INTO Courses (CourseID, CourseName, StudentID) VALUES
(101, 'Math', 1), -- Valid: StudentID 1 exists
(102, 'Physics', 2); -- Valid: StudentID 2 exists
-- This will FAIL
INSERT INTO Courses (CourseID, CourseName, StudentID) VALUES
(103, 'Chemistry', 5); -- Error: StudentID 5 does not exist in Students table
7️⃣ Why Are They Important?
💡 In short: