tags:

views:

49

answers:

3

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?
+3  A: 

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 valid user_id from the Users table, and a valid movie_id from the Movies table. With Foreign keys enforces, I could not delete a record from Users or Movies. If I didn't have foreign keys, I could delete those records. Then if I did a SELECT ... JOIN on Favorites it would break.

See Wikipedia.

Daniel A. White
Why is it used? I've had multiple tables with many-to-many relationships, and I've worked 'just fine' without defining these relationships explicitly.
Delan Azabani
Basically it helps keep your data clean.
Daniel A. White
So... this basically forces MySQL to check to see that the ID exists, and throws an error, failing to insert the record if it doesn't exist?
Delan Azabani
If so, if I delete, say, a 'user', with this method will all records related to that user be automatically deleted? Or must I still do that myself?
Delan Azabani
It depends on the implementation.
Daniel A. White
*A foreign key is a reference to a primary key* - It doesn't have to reference a primary key. In InnoDB you can reference any column(s) for which there is an index with the column(s) as the left-most prefix.
Mark Byers
“will all records related to that user be automatically deleted?” they can be, if you ask for it by using an `ON DELETE CASCADE` foreign key. Either way, ensuring there are no ‘dangling references’ to now-deleted rows is vital, otherwise your application is likely to behave strangely and inconsistently. Whilst you might think your application will never delete one without the other, in practice it's extremely easy to leave a corner case or a temporary test where it happens once, causing difficult-to-debug weirdness in the future.
bobince
+2  A: 

A foreign key describes a relationship between two tables. It has many benefits:

  • You can enforce that if a value is in the one table then it must also exist in the other table. Any attempt to break this constraint will give an error.
  • It allows database administrators or programmers to more easily understand the relationship between the tables just by looking at the table definitions.
  • It allows tools to inspect the schema and draw diagrams showing the relations between the tables, or create classes where the children of an object are accessible from the parent via members.
  • In InnoDB adding a foreign key also automatically adds an index on that column so that the join can be made efficiently in either direction. (Source)

If you are using MyISAM then foreign keys are not supported.

Mark Byers
A: 

You can also add the ability to cascade when a related record is deleted. For example if I have a library table with many books in a related "book" table and I delete a given library from my library table its' dependent book records will also be deleted.

Collin White