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: