SQL Foreign key with Example

aimtocode

Foreign Key:

Foreign keys are the columns of a table that points to the primary key of another table. They act as a cross-reference between tables.

Example:

In the below example the Stu_Id column in Course_enrollment table is a foreign key as it points to the primary key of the Student table.

Course_enrollment table:

Course_Id Stu_Id
C01 101
C02 102
C03 101
C04 102

Student table:

Stu_Id Stu_Name Stu_Age
101 Prayag 21
102 Rakesh 22
103 Pankaj 26

Note: Practically, the foreign key has nothing to do with the primary key tag of another table, if it points to a unique column (not necessarily a primary key) of another table then too, it would be a foreign key. So, a correct definition of foreign key would be: Foreign keys are the columns of a table that points to the candidate key of another table.


Read Also:


aimtocode