softwaretips4u Tips that Transform
← Back to Homepage ← Back to Articles

Primary Key vs Foreign Key in SQL

Primary keys and foreign keys are essential for maintaining data integrity and relationships between tables in a relational database.

🔹 Primary Key

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

🔹 Foreign Key

CREATE TABLE Enrollments (
    enrollment_id INT PRIMARY KEY,
    student_id INT,
    course_id INT,
    FOREIGN KEY (student_id) REFERENCES Students(student_id)
);

🔹 Key Differences

Feature Primary Key Foreign Key
Purpose Unique identity Relationship between tables
NULL Allowed? ❌ No ✅ Yes
Uniqueness Must be unique Can repeat
Count per Table Only 1 Many allowed
← Back to Articles | 🏠 Back to Homepage