What is a foreign key in MySQL?

A foreign key is a column in one table that points to the primary key of another table. It links the two tables and stops wrong values.

CREATE TABLE students (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  course_id INT,
  FOREIGN KEY (course_id) REFERENCES courses(id)
);

Now a student cannot get a course_id that does not exist in courses, and a course that has students cannot be deleted by mistake. The tables must use InnoDB. See MySQL JOINs.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.