sql

MySQL Foreign key constraint

--TABLE WITHOUT FOREIGN KEY
CREATE TABLE Student(
    Id INT AUTO_INCREMENT PRIMARY KEY,
    FullName VARCHAR(100) NOT NULL
)

--TABLE WITH FOREIGN KEY
CREATE TABLE StudentDetails(
    Id INT AUTO_INCREMENT PRIMARY KEY,
    EmailId varchar(100) NOT NULL,
    StudentId INT,
    CONSTRAINT fk_Student FOREIGN KEY (StudentId) REFERENCES Student(Id)
)

You can create a One-To-Many relationship between tables by adding Foreign key constraint on the child table. You can use the primary key of the master table as a foreign key of the child table.

In the above code snippet, we have created two tables named 'Student' and 'StudentDetails'. 'Student' table has a primary key named 'Id' where 'StudentDetails' has a column 'StudentId' which is being used as the foreign key and it is referenced from 'Student' table 'Id' column.

Was this helpful?