In an answer on Stack Overflow, I saw this code:
CREATE TABLE Favorites (
user_id INT NOT NULL,
movie_id INT NOT NULL,
PRIMARY KEY (user_id, movie_id),
FOREIGN KEY (user_id) REFERENCES Users(user_id),
FOREIGN KEY (movie_id) REFERENCES Movies(movie_id)
);
I’ve never used the ‘foreign key’ relationship keyword before.
- What is it?
- Why do people use it?
- Does it provide any benefit apart from semantics?
A foreign key is a reference to a primary key in another table or the table itself. It is used for what is called referential integrity. Basically in your table provided, for a Record to be inserted into
Favorites– you would have to supply a validuser_idfrom theUserstable, and a validmovie_idfrom theMoviestable. With Foreign keys enforces, I could not delete a record fromUsersorMovies. If I didn’t have foreign keys, I could delete those records. Then if I did aSELECT ... JOINonFavoritesit would break.See Wikipedia.