A beginners\' question about foreign key in MySQL.
In w3school it says,
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.<
It's not strictly needed for the query, it's true. It exists for several reasons:
(1) is probably the important one of the three. This is called referential integrity. It means that if there is a value in a foreign key there will be a corresponding record with that value as a primary key in the parent table.
That being said, not all databases support referential integrity (eg MySQL/MyISAM tables) and those that do don't necessarily enforce it (for performance reasons).
The Foreign is used for referential integrity.
See An introduction to foreign keys and referential integrity in MySQL
So if I can use WHERE for linking the tables, what is the main purpose of having foreign key?
Because WHERE
clause is not limited to equijoins on foreign keys.
Say, if you have a table which describes price ranges and discounts, you use this complex condition to join the tables:
SELECT *
FROM Goods
JOIN PriceRange
ON PriceRange.Price =
(
SELECT MAX(Price)
FROM PriceRange
WHERE PriceRange.Price <= Goods.Price
)
You cannot link these table with a foreign key relationship, but you can easily join them.
See this entry in my blog for more details:
The pk-to-pk binding, though, is still important. A FOREIGN KEY
can assure you that the entitie you are linking are described by your relational model.
With a FOREIGN KEY
-backed design, you cannot declare a relationship to an entity whose PRIMARY KEY
is absent in the table that describes that entity.
SQL Server
can even take this fact into account and optimize the certain types of queries.
Say, this query:
SELECT f.*
FROM t_foreign f
WHERE f.pid IN
(
SELECT id
FROM t_primary p
)
will not even look into t_primary
if the FOREIGN KEY
relationship is defined between t_foreign
and t_primary
.
See this article for more details:
The primary purpose of a WHERE clause is to limit the rows returned by the query. See SELECT Syntax.
Primary key/Foreign key relationships maintain referential integrity and with proper indexing increase the performance of queries. (See Pete OHanlon's explanation, above and JOIN Types)