Account
Categories

Foreign Key


A Foreign Key is a column or a combination of columns in a table whose values reference the Primary Key of another table. For example,suppose there are two tables:

1. students table, which contains columns: Roll ID (Primary Key), Name, and Age.
2. student_details table, which contains columns: Roll ID (Foreign Key), Course, and Year.
Here, the Roll ID field in the student_details table is the Foreign Key because it references the Roll ID field in the students table, where it is defined as the Primary Key.
This ensures that each record in the student_details table is properly linked to an existing student in the students table.

Note that:

  • A Foreign Key maintains referential integrity, which means values in the Foreign Key field must match values in the referenced Primary Key field.

  • It prevents invalid data entry and ensures that relationships between tables remain consistent.

Syntax:

CREATE TABLE table_name (
    column_name data_type,
    CONSTRAINT fk_name FOREIGN KEY (column_name) REFERENCES other_table_name (other_column_name)
);