HomeMYSQLWhat is a Primary key vs Foreign key

What is a Primary key vs Foreign key

Let’s break it down clearly:


Primary Key (PK):

  • Definition: A primary key is a column (or a set of columns) in a table that uniquely identifies each row.
  • Characteristics:
    1. Must be unique for every row.
    2. Cannot contain NULL values.
    3. A table can have only one primary key.
  • Example:
student_idnameage
1Alice20
2Bob21

Here, student_id is a primary key because it uniquely identifies each student.


Foreign Key (FK):

  • Definition: A foreign key is a column (or set of columns) in a table that references the primary key in another table. It is used to maintain a relationship between two tables.
  • Characteristics:
    1. Can have duplicate values.
    2. Can have NULL values (unless specified otherwise).
    3. Enforces referential integrity between tables.
  • Example:

Table: Courses

course_idcourse_name
101Math
102Physics

Table: Enrollments

enrollment_idstudent_idcourse_id
11101
22102

Here:

  • course_id in Enrollments is a foreign key referencing course_id in Courses.
  • student_id in Enrollments could also be a foreign key referencing student_id in Students.

Key difference:

  • Primary key: uniquely identifies a row in its own table.
  • Foreign key: creates a link to a primary key in another table.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *