MySQL Tutorial
A FOREIGN KEY
in MySQL is a constraint used to link records between two tables. It enforces a relationship by ensuring the values in a column (or a set of columns) match the values in a column from another table, usually the Primary Key of the referenced table.
ON UPDATE
and ON DELETE
.CREATE TABLE child_table ( column1 data_type, column2 data_type, FOREIGN KEY (column_name) REFERENCES parent_table(primary_key_column) );
CREATE TABLE child_table ( column1 data_type, column2 data_type, CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES parent_table(primary_key_column) );
The following SQL creates a FOREIGN KEY
on the "course_id" column when the "courses" table is created:
To create a FOREIGN KEY
constraint on the "couser_id" column when the "courses" table is already created, use the following SQL:
fk_course
→ This is the name of the foreign key constraint.course_id
→ Column in the students
table.courses(course_id)
→ Column in the courses
table, which is a Primary Key.To drop a FOREIGN KEY
constraint, use the following SQL:
DROP FOREIGN KEY fk_course
removes the foreign key relationship.students
table will no longer have any restrictions on the course_id
values.